使用流的重构方法

Rewowrking method with stream usage

是否可以仅使用流来修改以下方法?

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;
}

不仅可行,而且非常简单:

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));
}

这是您学习的另一种方式。

  • 流线
  • 以逗号分隔并流式传输数组。
  • 基于索引项 3 的分组。
  • 并通过收集器对项目 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]))));
}