SoFunction
Updated on 2025-04-13

Java: Three methods to determine whether there is intersection between two List<String> sets

Judge two in JavaList<String>Whether the set has intersections, the following methods can be used:

Method 1: Use the retainAll method

retainAllThe method retains the same elements in the set as another set. If the set changes, it means there is an intersection.

List&lt;String&gt; list1 = ("a", "b", "c");
List&lt;String&gt; list2 = ("c", "d", "e");

List&lt;String&gt; temp = new ArrayList&lt;&gt;(list1);
boolean hasIntersection = (list2);  // Return true to indicate that there is an intersection
("Whether there is an intersection:" + hasIntersection);

Method 2: Use Stream and anyMatch

Streaming operations using Java 8 are simpler.

List&lt;String&gt; list1 = ("a", "b", "c");
List&lt;String&gt; list2 = ("c", "d", "e");

boolean hasIntersection = ().anyMatch(list2::contains);
("Whether there is an intersection:" + hasIntersection);

Method 3: Use Set to improve performance

If the collection is large, useSetIt will be more efficient.

List&lt;String&gt; list1 = ("a", "b", "c");
List&lt;String&gt; list2 = ("c", "d", "e");

Set&lt;String&gt; set = new HashSet&lt;&gt;(list1);
boolean hasIntersection = ().anyMatch(set::contains);

("Whether there is an intersection:" + hasIntersection);

Selection by

  • retainAll methodSimple and direct, but will modify the original collection.
  • StreamIt is a functional programming style, and the code is simpler.
  • Use SetAvoid linear search and is suitable for large-scale data collections.

Summarize

This is the article about java's three methods of judging whether there is intersection between two List<String> sets. For more related java's judging of List<String> sets, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!