Chu*_*rap 9 java java-8 java-stream collectors
我有一个A
类似的列表
class A {
private Integer keyA;
private Integer keyB;
private String text;
}
Run Code Online (Sandbox Code Playgroud)
我想转移aList
到嵌套Map
映射由keyA
和keyB
所以我创建下面的代码.
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.collectingAndThen(Collectors.groupingBy(A::getKeyA), result -> {
Map<Integer, Map<Integer, List<A>>> nestedMap = new HashMap<Integer, Map<Integer, List<A>>>();
result.entrySet().stream().forEach(e -> {nestedMap.put(e.getKey(), e.getValue().stream().collect(Collectors.groupingBy(A::getKeyB)));});
return nestedMap;}));
Run Code Online (Sandbox Code Playgroud)
但我不喜欢这段代码.
我想如果我使用flatMap
,我可以更好地编码.
但我不知道如何使用flatMap
这种行为.
Tag*_*eev 14
似乎你只需要一个级联groupingBy
:
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.groupingBy(A::getKeyA,
Collectors.groupingBy(A::getKeyB)));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2731 次 |
最近记录: |