English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to calculate the intersection of two collections in Java.
To understand this example, you should understand the followingJava ProgrammingTopic:
import java.util.HashSet; import java.util.Set; class Main { public static void main(String[] args) { //Create the first collection Set<Integer> primeNumbers = new HashSet<>(); primeNumbers.add(2); primeNumbers.add(3); System.out.println("Prime numbers: ", + primeNumbers); //Create the second collection Set<Integer> evenNumbers = new HashSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("Even numbers: ", + evenNumbers); //Intersection of two collections evenNumbers.retainAll(primeNumbers); System.out.println("Intersection of two collections: ", + evenNumbers); } }
Output Result
Prime numbers: [2, 3] Even numbers: [2, 4] Intersection of two collections: [2]
In the above example, we created two collections named primeNumbers and evenNumbers. We implemented this collection using the HashSet class. Note this line,
evenNumbers.retainAll(primeNumbers);
In this example, we use the retainAll() method to obtain the intersection of two collections.
import java.util.HashSet; import java.util.Set; import com.google.common.collect.Sets; class Main { public static void main(String[] args) { //Create the first collection Set<String> backend = new HashSet<>(); backend.add("Java"); backend.add("JavaScript"); System.out.println("Backend language: ", + backend); //Create the second collection Set<String> frontend = new HashSet<>(); frontend.add("JavaScript"); frontend.add("CSS"); System.out.println("Front-end Language: ", + frontend); Set<String> intersect = Sets.intersection(backend, frontend); System.out.println("General Language: ", + intersect); } }
Output Result
Back-end Language: [Java, JavaScript] Front-end Language: [JavaScript, CSS] General Language: [JavaScript]
In the above example, we use the Guava library to get the intersection of two collections. To run this program, you need to implement it by adding the Guava library to the dependencies.
Here, we use the intersection() method of the Sets class from the Guava library.