In this example we will show how to obtain common elements of two LinkedHashSet.
Source Code
package com.beginner.examples;
import java.util.LinkedHashSet;
public class RetainAllExample {
public static void main(String a[]){
LinkedHashSet set1 = new LinkedHashSet();
//add elements
set1.add("1");
set1.add("2");
set1.add("3");
System.out.println("set1 : " + set1);
LinkedHashSet set2 = new LinkedHashSet();
//add elements
set2.add("4");
set2.add("5");
set2.add("2");
System.out.println("set2 : " + set2);
// get common elements
set1.retainAll(set2);
System.out.println("Common elements : " + set1);
}
}
Output:
set1 : [1, 2, 3]
set2 : [4, 5, 2]
Common elements : [2]
References
Imported packages in Java documentation: