Java 8 Stream groupingby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27969584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Stream groupingby
提问by Omer
I have List<Map<String, String>>
each item in the list is a map e.g
我List<Map<String, String>>
在列表中的每个项目都是一张地图,例如
companyName - IBM
firstName - James
country - USA
...
I would like create a Map<String, List<String>>
where it maps companyName to a list of of firstName
e.g
我想创建一个Map<String, List<String>>
将 companyName 映射到 firstName 列表的位置,例如
IBM -> James, Mark
ATT -> Henry, Robert..
private Map<String,List<String>> groupByCompanyName(List<Map<String, String>> list) {
return list.stream().collect(Collectors.groupingBy(item->item.get("companyName")));
}
but this will create Map<String, List<Map<String, String>>
(mapping comanyName to a list of maps)
但这将创建Map<String, List<Map<String, String>>
(将 comanyName 映射到地图列表)
how to create a Map<String, List<String>>
?
如何创建一个Map<String, List<String>>
?
采纳答案by Eran
Haven't tested it, but something like this should work:
还没有测试过,但这样的事情应该可以工作:
Map<String, List<String>> namesByCompany
= list.stream()
.collect(Collectors.groupingBy(item->item.get("companyName"),
Collectors.mapping(item->item.get("firstName"), Collectors.toList())));
回答by nitishagar
You can use the form:
您可以使用以下表格:
groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
i.e. specify the values from the map in the downstream to be taken as list. The documentation has good example for it (here).
即指定下游地图中的值作为列表。文档有很好的例子(这里)。
downstream
being something like - mapping(item->item.get(<name>), toList())
downstream
像 - mapping(item->item.get(<name>), toList())
回答by Davidw
The groupingBy method yields a map whose values are lists. If you want to process those lists in some way, supply a "downstream collector" In you case, you don't want a List as the value, so you need to provide a downstream collector.
groupingBy 方法生成一个值为列表的映射。如果您想以某种方式处理这些列表,请提供一个“下游收集器”。在这种情况下,您不需要 List 作为值,因此您需要提供一个下游收集器。
To manipulate the Map, you can use the static method mapping in Collectors file:
要操作 Map,您可以使用 Collectors 文件中的静态方法映射:
Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
Collector<? super U, A, R> downstream)
It basically generates a collector by applying a function to the downstream results and passes the function to another collector.
它基本上通过将一个函数应用于下游结果并将该函数传递给另一个收集器来生成一个收集器。
Collectors.mapping(item->item.get("firstName"), Collectors.toList())
This will return a downstream collector which will achieve what you want.
这将返回一个下游收集器,它将实现您想要的。