我有两个对象。第一个:
public final class Object1 {
private String a;
private String b;
// constructor getter and setter
}
第二个:
public class Object2 {
private BigDecimal value1;
private BigDecimal value2;
// constructor getter and setter
}
我有Map<Object1, Object2>
:
Object1{a="15", b="XXX"}, Object2{value1=12.1, value2=32.3}
Object1{a="15", b="YYY"}, Object2{value1=21.1, value2=24.3}
Object1{a="16", b="AAA"}, Object2{value1=34.1, value2=45.3}
Object1{a="15", b="BBB"}, Object2{value1=23.1, value2=65.3}
Object1{a="15", b="DDD"}, Object2{value1=23.1, value2=67.3}
Object1{a="17", b="CCC"}, Object2{value1=78.1, value2=2.3}
........
我想将此地图与Object2列表中的相同a分组,如:
a="15", {{value1=12.1, value2=32.3}, {value1=21.1, value2=24.3}, {value1=23.1, value2=65.3}, {value1=23.1, value2=67.3}},
a="16", {{value1=34.1, value2=45.3}}
...
我尝试这样的事情:
Map<String, List<Object2>> map1 = map.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().getA(), list of object with this key);
答案 0 :(得分:5)
yourMap.entrySet()
.stream()
.collect(Collectors.groupingBy(e -> e.getKey().getA(),
Collectors.mapping(Entry::getValue, Collectors.toList())))