How to Retain Same Elements from Two HashSets in Java


In this example,we will learn how to compare two HashSets and retain the same elements which are same on two sets.

Source Code

package com.beginner.examples;

import java.util.HashSet;

public class RetainSet {

	public static void main(String[] args) {
		//Create HashSet Object
		HashSet hashSet1 = new HashSet();
		hashSet1.add("Alice");
		hashSet1.add("Bob");
		hashSet1.add("Jack");
		
		//Create another HashSet Object
		HashSet hashSet2 = new HashSet();
		hashSet2.add("Hello");
		hashSet2.add("Hi");
		hashSet2.add("Bob");
		
		/*
		 * Use the method retainAll() to compare two sets 
		 * and retain elements which are same on both sets.
		 */
		hashSet1.retainAll(hashSet2);
		System.out.println(hashSet1);
	}

}

Output:

[Bob]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments