Reputation: 2085
Let's say I have 2 ArrayList of Points:
(0,2)->(0,3)->(0,4)
(0,2)->(0,3)->(0,6)
And I want to obtain a new list : (0,2)->(0,3)
How do I do that?
current solution
Using two foreach loops to compare the two lists, element by element. I think it's a very inefficient way. Are there any other ways?
Upvotes: 2
Views: 84
Reputation: 1607
If large lists, add elements of one list to a HashSet
and iterate other while keep adding elements to the new list which the 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());
Time complexity, Adding to Set = O(n), Iterating list = O(k) time hashset lookup O(1) ~ overall O(n)
Upvotes: 0
Reputation: 62864
You can use the List#retainAll(Collection<?> c)
method, which:
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);
Upvotes: 6