我现在正在学习java 8 stream,我很好奇有没有什么方便的方法来转换List<Pair<A,B>>
至 List<Pair<A,List<B>>>
, 也就是按键合并pair的值?
我曾经想过使用forEach
方法,但它似乎效率较低,因为我需要遍历新列表来检查对的 key 。
最佳答案
我建议使用 LinkedHashMap
(它也支持条目的插入顺序)而不是 List<Pair<>>
.使用它你可以简单地使用 Collectors.groupingBy()
和 Collectors.mapping()
实现这一目标:
List<Pair<A, B>> list = ...;
Map<A, List<B>> result = list.stream()
.collect(Collectors.groupingBy(Pair::getKey, LinkedHashMap::new,
Collectors.mapping(Pair::getValue, Collectors.toList())));
但是如果你真的需要 List<Pair<>>
您可以将 map 转换回:
List<Pair<A, B>> list = ...;
List<Pair<A, List<B>>> result = list.stream()
.collect(Collectors.groupingBy(Pair::getKey, LinkedHashMap::new,
Collectors.mapping(Pair::getValue, Collectors.toList())))
.entrySet().stream()
.map(e -> new Pair<>(e.getKey(), e.getValue()))
.collect(Collectors.toList());
请记住,您使用此解决方案迭代两次(第一次是列表,第二次是 map )。
除此之外,如果您还想删除 B
的重复项你可以使用 LinkedHashSet
(这也保持秩序)。为此,您只需要更改映射下游收集器:
List<Pair<A, B>> list = ...;
Map<A, Set<B>> result = list.stream()
.collect(Collectors.groupingBy(Pair::getKey, LinkedHashMap::new,
Collectors.mapping(Pair::getValue, Collectors.toCollection(LinkedHashSet::new))));
关于java - 使用流根据键值合并 List<Pair<A,B>> 到 List<Pair<A,List<B>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203304/