gpt4 book ai didi

java - 是否可以改进将列表转换为排序 map ?

转载 作者:行者123 更新时间:2023-11-30 06:49:11 24 4
gpt4 key购买 nike

现在我有这样的方法:

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 进行排序。

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

最佳答案

您可以使用 Collectors.groupingBymapFactory 作为参数的变体:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com