ohw*_*ppp 3 java java-8 java-stream
我有List<ServiceName> servicesNames
和ServiceName有这样的结构:
public class ServiceName {
private Map<String, String> names;
}
Run Code Online (Sandbox Code Playgroud)
names
带有语言和名称的Hashmap 在哪里- 通常是几个值.
我正试图得到Map<String lang, List<String> names>>
- 其中关键是语言和价值是给定语言的所有名称的列表List<ServiceName>
.
这是我到目前为止所得到的但是可以把它放在一起 - 得到编译错误:
servicesNames
.stream()
.map(x -> x.getNames())
.flatMap(x -> x.entrySet().stream())
.collect(x -> Collectors.groupingBy());
Run Code Online (Sandbox Code Playgroud)
编辑:我能够得到这个:
List<Map.Entry<String, String>> collect1 = servicesNames
.stream()
.map(x -> x.getNames())
.flatMap(x -> x.entrySet().stream())
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
但是不知道在使用flatmap之后实际按键分组所有值...
您需要Collectors.groupingBy
按键对值进行分组,并将映射应用于下游Collectors.mapping
.
基于lambda的方法:
Map<String, List<String>> map = servicesNames
.stream()
.flatMap(service -> service.getNames().entrySet().stream())
.collect(groupingBy(e -> e.getKey(), mapping(e -> e.getValue(), toList())));
Run Code Online (Sandbox Code Playgroud)
方法基于参考的方法:
Map<String, List<String>> map = servicesNames
.stream()
.map(ServiceName::getNames)
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1437 次 |
最近记录: |