Java gets the intersection of two List collections

Get the intersection of two List collections

You can use the retainAll method in Java to get the intersection of two Lists:

Suppose there are two collections list1 and list2 of List type, the code is as follows:

List<String> list1 = new ArrayList<>();
list1.add("apple");
list1.add("banana");
list1.add("orange");

List<String> list2 = new ArrayList<>();
list2.add("banana");
list2.add("orange");
list2.add("watermelon");

Here is the code to get the intersection of two collections:

List<String> intersection = new ArrayList<>(list1);
intersection.retainAll(list2);
System.out.println(intersection);

The output is:

[banana, orange]

Among them, the retainAll method will modify the intersection collection so that it only contains the intersection of the two collections. In this example, the intersection collection initially contains the elements of the list1 collection, and then filters out elements that do not belong to the list2 collection through the retainAll method, and finally obtains the intersection of the two collections.

Guess you like

Origin blog.csdn.net/A_yonga/article/details/129562565