首先,您应该在问题中提供一个完整的可编译示例,例如:
Stream<String> filecontent = Stream.of("foo in bar is foo", "bar in bar is not foo");
Map<String, Long> result = filecontent.flatMap(line -> Stream.of(line.split("\\s+")))
.map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
然后要reduce,你需要使用Map对象来reduce(为简洁起见使用Java HashMap,这不是这种情况下最有效的数据结构):
Stream<String> filecontent = Stream.of("foo in bar is foo", "bar in bar is not foo");
Map<String, Long> result = filecontent.flatMap(line -> Stream.of(line.split("\\s+")))
.map((word) -> singletonMap(word.toLowerCase(), 1L))
.reduce(new HashMap<>(), (map1, map2) -> {
for (Map.Entry<String, Long> entry: map2.entrySet()) {
map1.put(entry.getKey(), map1.getOrDefault(entry.getKey(), 0L) + entry.getValue());
}
return map1;
});
这将首先创建一个新的空 HashMap,然后为每个新单词创建一个单例 Hashmap,并在每个 reduce 步骤中将这样的单例映射合并到原始 hashmap 中。如果你想使用并行流来做到这一点,你需要在 reduce 步骤中创建一个新的 map:
Map<String, Long> tempResult = new HashMap<>(map1);
for (Map.Entry<String, Long> entry: map2.entrySet()) {
tempResult.put(entry.getKey(), map1.getOrDefault(entry.getKey(), 0L) + entry.getValue());
}
return tempResult;