Use the retainAll() method of the HashSet class to obtain the intersection of two collections
HashSet is a collection class in Java that is used to store a set of unique objects. The retainAll() method is a method provided by the HashSet class and is used to obtain the intersection of two HashSets.
In Java, a collection is a commonly used data structure that can be used to store multiple objects. HashSet is a commonly used concrete implementation in collection classes. It implements the function of storing and retrieving objects through hash tables. The characteristic of HashSet is that it does not allow duplicate elements and has no fixed order.
The following is a sample code that uses the retainAll() method of the HashSet class to obtain the intersection of two sets:
import java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { // 创建第一个HashSet集合 HashSet<String> set1 = new HashSet<>(); set1.add("apple"); set1.add("banana"); set1.add("orange"); // 创建第二个HashSet集合 HashSet<String> set2 = new HashSet<>(); set2.add("orange"); set2.add("watermelon"); set2.add("kiwi"); // 使用retainAll()方法获取两个集合的交集 set1.retainAll(set2); // 输出交集的元素 System.out.println("两个集合的交集为:"); for (String element : set1) { System.out.println(element); } } }
Run the above code, the output result is:
两个集合的交集为: orange
Passed As can be seen from the running results, the intersection of two sets can be obtained using the retainAll() method of HashSet. In the above example, the first HashSet collection contains the three elements "apple", "banana" and "orange", and the second HashSet collection contains the three elements "orange", "watermelon" and "kiwi". After calling the set1.retainAll(set2) method, there is only one "orange" element left in the set1 collection, which is the intersection of the two collections.
Using the retainAll() method of HashSet can easily obtain the intersection of two sets, which is very useful in actual development. For example, you can use it to perform mathematical operations on two sets, such as intersection, union, difference, etc.
To summarize, using the retainAll() method of the HashSet class can easily obtain the intersection of two sets. This method is very useful in actual development and can play an important role when dealing with collection-related problems.
The above is the detailed content of Use the retainAll() method of the HashSet class to obtain the intersection of two sets. For more information, please follow other related articles on the PHP Chinese website!