我想计算一个句子中每个字母的出现次数,并将结果存储在Map<Character, Integer>
中。这可以通过简单的循环轻松完成,但作为练习我想用流编写它。我想过使用collect(toMap())
生成一个地图,其值是字符本身(所以我使用Function.identity()
)和出现次数。我想出了以下(非编译)代码:
"a simple sentence".chars()
.collect(toMap(Collectors.partitioningBy(Function.identity(),
Collectors.counting())));
答案 0 :(得分:3)
尝试以下方法:
String string ="a simple sentence";
Map<String, Long> map =
Arrays.stream(string.split("")).
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
答案 1 :(得分:3)
你真的很接近,为了完成你的开始,你需要使用mapToObj
中间操作和groupingBy
收集器而不是partitioningBy
,如下所示:
Map<Character, Long> result = "a simple sentence".chars()
.mapToObj(c -> (char) c)
.collect(groupingBy(Function.identity(),
counting()));
或者如果你想让地图键成为字符串,那么你可以这样做:
Map<String, Long> result = "a simple sentence".chars()
.mapToObj(c -> String.valueOf((char) c))
.collect(groupingBy(Function.identity(),
counting()));
或者如果您希望出现除空白字符以外的所有字符:
Map<String, Long> result = "a simple sentence".chars()
.filter(c -> !Character.isSpaceChar(c))
.mapToObj(c -> String.valueOf((char) c))
.collect(groupingBy(Function.identity(),
counting()));
或使用模式:
Map<String, Long> result =
Pattern.compile("\\s+")
.splitAsStream("a simple sentence")
.flatMap(s -> Arrays.stream(s.split("")))
.collect(groupingBy(Function.identity(),
counting()));
使用模式的更高效版本:
Map<String, Long> result =
Pattern.compile("")
.splitAsStream("a simple sentence")
.filter(s -> !s.trim().isEmpty())
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));