现在我有这样的方法:
public static Map<String, Long> getSortedMap(List<String> wordsList) {
Map<String, Long> countedWords = wordsList.stream()
.collect(
Collectors.groupingBy(Function.identity(), Collectors.counting())
);
return new TreeMap<>(countedWords);
}
将字符串列表转换为映射,其中键是列表中的唯一字符串,值是该字符串在列表中重复的次数。然后它按键对 map 进行排序。
- 这可以在一个流操作中重写吗?
- 是否可以提高执行速度?
最佳答案
您可以使用 Collectors.groupingBy以 mapFactory
作为参数的变体:
public static Map<String, Long> getSortedMap(List<String> wordsList) {
return wordsList.stream()
.collect(
Collectors.groupingBy(Function.identity(),
TreeMap::new,
Collectors.counting())
);
}
关于java - 是否可以改进将列表转换为排序 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43180597/