是否有可能将转换列表改进为已排序的地图?

时间:2017-04-03 09:07:05

标签: java collections java-stream

现在我有这样的方法:

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);
}

将字符串列表转换为映射,其中键是列表中的唯一字符串,以及值 - 此字符串在列表中重复的次数。然后按键对地图进行排序。

  1. 可以在一个流操作中重写吗?
  2. 是否有可能提高执行速度?

1 个答案:

答案 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())
            );
}