Adam I
Adam I

Reputation: 13

Rewowrking method with stream usage

Is there a possibility to rework below method using only streams?

public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    Map<String, Long> namesWithCounts = new HashMap<>();
    for (String line : lines) {
        String[] words = line.split(",");
        String name = words[3];
        Long count = Long.parseLong(words[4]);
        if (namesWithCounts.containsKey(name)) {
            namesWithCounts.put(name, namesWithCounts.get(name) + count);
        } else {
            namesWithCounts.put(name, count);
        }
    }
    return namesWithCounts;
}

Upvotes: 0

Views: 59

Answers (2)

WJS
WJS

Reputation: 40057

And here is yet another way for your learning enjoyment.

  • stream the lines
  • split on a comma and stream the arrays.
  • group based on indexed item 3.
  • and sum via a collector on item 4.
public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    return lines.stream().map(line -> line.split(","))
        .collect(Collectors.groupingBy(arr -> arr[3],
                 Collectors.summingLong(arr -> Long.valueOf(arr[4]))));
}


Upvotes: 3

MTCoster
MTCoster

Reputation: 6145

Not only is it possible, it’s surprisingly straightforward:

public static Map<String, Long> getPeopleFromLines(List<String> lines) {
    return lines.stream()
            .map(line -> line.split(","))
            .collect(Collectors.toMap(
                    words -> words[3],
                    words -> Long.parseLong(words[4]),
                    Long::sum));
}

Upvotes: 2

Related Questions