【发布时间】:2019-01-15 04:24:30
【问题描述】:
我有一个字符串,我想按降序对其进行字数统计。我的代码如下:
String[] line = "some text some spaces".split(" ");
Map<String, Long> map1 = Arrays.stream(line).stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<String, Long> map2 = map1.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), (v1, v2) -> v2, LinkedHashMap::new));
上面给了我一个单词出现次数的降序排列。是否可以只执行一次此操作,我的意思是将第 2 行和第 3 行合并为一个。这将要求我只创建一个流。
非常感谢您。
【问题讨论】:
-
我认为没有两个流就不可能做到这一点。
标签: java java-8 word-count