英文:
How to access the map Collecters.toMap is collecting to?
问题
collect(Collectors.toMap(String::toString, str -> {map.get(str)+1})
我想在地图中维护字符串的计数。是否有办法访问Collector正在收集的地图?
英文:
collect(Collectors.toMap(String::toString, str -> {map.get(str)+1})
I want to maintain counts of strings in a map. Is there anyway to access the map the Collector is collecting into?
答案1
得分: 3
你可以尝试制作类似这样的代码:
List<String> list1 = Arrays.asList("red", "blue", "green");
Map<String, Integer> map1 = list1.stream().collect(Collectors.toMap(String::toString, t -> t.length()));
但是,如果你的列表中有重复的值,你应该将它们合并:
List<String> list2 = Arrays.asList("red", "red", "blue", "green");
Map<String, Integer> map2 = list2.stream()
.collect(Collectors.toMap(String::toString, t -> t.length(), (line1, line2) -> line1));
而且,如果你想让你的代码更高效,你可以使用并行流和并发映射,但你必须确保没有空值(关于并发映射的更多信息,请参考官方文档):
List<String> list3 = Arrays.asList("red", "red", "blue", "green", null);
Map<String, Integer> map3 = list3.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toConcurrentMap(String::toString, t -> t.length(), (line1, line2) -> line1));
希望对你有所帮助
英文:
You can try to make something like this :
List<String> list1 = Arrays.asList("red", "blue", "green");
Map<String, Integer> map1 = list1.stream().collect(Collectors.toMap(String::toString, t -> t.length()));
But if you have a duplicate value in your list you should merge them :
List<String> list2 = Arrays.asList("red", "red", "blue", "green");
Map<String, Integer> map2 = list2.stream()
.collect(Collectors.toMap(String::toString, t -> t.length(), (line1, line2) -> line1));
And, if you want to make your code more efficient you can use a parallel stream with concurrent map
but you have to ensure that you don't have a null value (for more information about the concurrent map you refer to the official documentation)
List<String> list3 = Arrays.asList("red", "red", "blue", "green", null);
Map<String, Integer> map3 = list3.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toConcurrentMap(String::toString, t -> t.length(), (line1, line2) -> line1));
I hope this is useful to you
专注分享java语言的经验与见解,让所有开发者获益!
评论