原理:利用set的retailAll方法
retainAll
是 Java 中 Set
接口的一个方法。该方法用于从当前集合中移除那些未包含在指定集合中的所有元素,即它修改了调用它的集合,使其只包含那些也包含在指定集合中的元素。
简单来说,retainAll
方法用于找到两个集合的交集。
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
set1.retainAll(set2);
System.out.println(set1); // 输出: [3, 4, 5]
代码
Map<String, List<Long>> map = new HashMap<>();
// 创建模拟数据
List<Long> ids = new ArrayList<>();
map.put("1",Arrays.asList(1L, 2L, 3L, 5L));
map.put("2",Arrays.asList(1L, 3L, 4L, 5L));
map.put("3",Arrays.asList(1L, 2L, 3L, 5L));
map.put("4",Arrays.asList(1L, 2L, 3L));
if (MapUtils.isNotEmpty(map)) {
Set<Long> intersectionSet = new HashSet<>(); // 创建交集
boolean allNotNull = true; // 用一个布尔值保存所有数组是否都不为空
for (Map.Entry<String, List<Long>> entry : map.entrySet()) {
List<Long> list = entry.getValue();
if (list != null && !list.isEmpty()) {
if(CollectionUtils.isEmpty(intersectionSet)){
// 如果运行到这一步是给交集赋初始值 此时必定是第一次循环
intersectionSet.addAll(list);
}else{
// 利用retainAll方法求交集
intersectionSet.retainAll(list);
}
} else {
// 只要遇到遇到空数组就可以退出循环 因为交集必定为空
allNotNull = false;
break;
}
}
if(allNotNull){
ids = new ArrayList<>(intersectionSet);
}
System.out.println(ids);
}
}
附言
如果有更加好的方法麻烦评论或者私信