我有以下类:
public class A{
public List<String> groups;
}
我试图建立一个Map<String, List<A>>
其中关键代表组。
我知道如何当A类属于一个组做:
List<A> aList = getAList();
Map<String, List<A>> aByGroupMap = aList.stream().parallel()
.collect(Collectors.groupingBy(a -> a.getGroup()));
但如何能适应以这样的方式,上面的代码,对象A被映射到多个组?例如,如果对象a1
所属的群体["G", "H", "I"]
和对象A2所属的组["H", "I"]
?
你可以尝试这样的事:
Map<String, List<A>> aByGroupMap = aList.stream()
.flatMap(a -> a.getGroups().stream()
.map(g -> new AbstractMap.SimpleEntry<>(g , a)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
或者,如果你有一个小先前已知的一套您的组像
Set<String> myGroups = Set.of("A","B","C");
你可以这样做:
Map<String,List<A>> map = new HashMap<>();
myGroups.forEach(g -> {
aList.stream().filter(a -> a.getGroups().contains(g)).forEach(a ->{
map.computeIfAbsent(g, s -> new ArrayList<>()).add(a);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句