stream 流 实现 多集合 取交集
题目描述:
提供多个数组,取出所有数组的 交集
示例:
输入:
[1,2,3,4,5,6]
[2,3,1,5,34]
[2,45,6]
...
[2,...]
输出:
[2]
思路:
- 获取流
- 对流进行取交集操作
- 将结果转成新的集合输出
源码:
具体逻辑代码
private Collection retain(Collection<Collection> c){
Optional result = c.parallelStream().reduce((m1, m2)->{
m1.retainAll(m2);
return m1;
});
return (Collection) result.get();
}
测试代码
@Test
public void testRetain(){
Collection collection = new ArrayList();
collection.add(4);
collection.add(2);
collection.add(2);
collection.add(8);
Collection collection2 = new ArrayList();
collection2.add(2);
collection2.add(2);
collection2.add(9);
collection2.add(4);
Collection collection3 = new ArrayList();
collection3.add(2);
collection3.add(2);
collection3.add(41);
collection3.add(7);
List<Collection> l = new ArrayList();
l.add(collection);
l.add(collection2);
l.add(collection3);
System.out.println(retain(l));
}
个人水平有限,如有问题,请各路大神指教留言,评论区讨论,虚心接纳
如果觉得有帮助,请点赞收藏,谢谢