Judge two in JavaList<String>
Whether the set has intersections, the following methods can be used:
Method 1: Use the retainAll method
retainAll
The method retains the same elements in the set as another set. If the set changes, it means there is an intersection.
List<String> list1 = ("a", "b", "c"); List<String> list2 = ("c", "d", "e"); List<String> temp = new ArrayList<>(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<String> list1 = ("a", "b", "c"); List<String> 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, useSet
It will be more efficient.
List<String> list1 = ("a", "b", "c"); List<String> list2 = ("c", "d", "e"); Set<String> set = new HashSet<>(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!