现在我有这样的方法:
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);
}
将字符串列表转换为映射,其中键是列表中的唯一字符串,以及值 - 此字符串在列表中重复的次数。然后按键对地图进行排序。
答案 0 :(得分:4)
您可以使用以mapFactory
作为参数的Collectors.groupingBy变体:
public static Map<String, Long> getSortedMap(List<String> wordsList) {
return wordsList.stream()
.collect(
Collectors.groupingBy(Function.identity(),
TreeMap::new,
Collectors.counting())
);
}