如何获取两个 ArrayList 的重复值?

How do I obtain the duplicated values of two ArrayLists?

假设我有 2 个点数组列表:

  1. (0,2)->(0,3)->(0,4)
  2. (0,2)->(0,3)->(0,6)

我想获取一个新列表:(0,2)->(0,3)

我该怎么做?

当前解

使用两个 foreach 循环逐个元素地比较两个列表。我认为这是一种非常低效的方式。还有其他方法吗?

您可以使用List#retainAll(Collection<?> c)方法,即:

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

List<Point> first = ...
List<Point> second = ...
first.retainAll(second);

如果列表很大,将一个列表的元素添加到 HashSet 并迭代其他列表,同时继续将元素添加到 HashSet contains

的新列表
List<Point> list1 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(0,2), new Point(0,3), new Point(0,4)}));
List<Point> list2 = new ArrayList<Point>(Arrays.asList(new Point[]{new Point(0,2), new Point(0,3), new Point(0,6)}));
Set<Point> setList1 = new HashSet<Point>(list1);
List<Point> intersection  = list2.stream().filter( l -> setList1.contains(l)).collect(Collectors.toList());

时间复杂度, 添加到 Set = O(n),迭代列表 = O(k) 时间 hashset 查找 O(1) ~ 整体 O(n)