如何访问正在收集的 Collectors.toMap 映射?

huangapple go评论84阅读模式
英文:

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

希望对你有所帮助 如何访问正在收集的 Collectors.toMap 映射?

英文:

You can try to make something like this :

List&lt;String&gt; list1 = Arrays.asList(&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;);
Map&lt;String, Integer&gt; map1 = list1.stream().collect(Collectors.toMap(String::toString, t -&gt; t.length()));

But if you have a duplicate value in your list you should merge them :

List&lt;String&gt; list2 = Arrays.asList(&quot;red&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;green&quot;);
Map&lt;String, Integer&gt; map2 = list2.stream()
        .collect(Collectors.toMap(String::toString, t -&gt; t.length(), (line1, line2) -&gt; 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&lt;String&gt; list3 = Arrays.asList(&quot;red&quot;, &quot;red&quot;, &quot;blue&quot;, &quot;green&quot;, null);
Map&lt;String, Integer&gt; map3 = list3.parallelStream()
        .filter(Objects::nonNull)
        .collect(Collectors.toConcurrentMap(String::toString, t -&gt; t.length(), (line1, line2) -&gt; line1));

I hope this is useful to you 如何访问正在收集的 Collectors.toMap 映射?

huangapple
  • 本文由 发表于 2020年4月4日 06:43:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61021508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定