Java – retainAll() method explanation with HashSet

In this article, we will discuss retainAll() method of Collection interface with HashSet

boolean retainAll(Collection c);remove/deletes all element/objects of invoking collection except specified collection

 

(i.e.; retaining specified collection and removing other objects from invoking collection)

1. retainAll() method of Collection interface

RetainAllMethodWithHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;

public class RetainAllMethodWithHashSet {

	public static void main(String[] args) {

		// creating HashSet object of type String
		HashSet<String> originalSet = new HashSet<String>();

		// adding elements to HashSet object - 4
		originalSet.add("Sundar Pichai");
		originalSet.add("Satya Nadella");
		originalSet.add("Shiv Nadar");
		originalSet.add("Shantanu Narayen");

		// Iterating using enhanced for-loop
		System.out.println("Iterating original set\n");
		for(String founder : originalSet) {
			System.out.println(founder);
		}

		// creating HashSet object of type String
		HashSet<String> retainableSet = new HashSet<String>();

		// adding elements to HashSet object - 3
		retainableSet.add("Narayan Murthy");
		retainableSet.add("Sundar Pichai");
		retainableSet.add("Shantanu Narayen");

		originalSet.retainAll(retainableSet);

		// Iterating using enhanced for-loop
		System.out.println("\n\n\nIterating original set,"
				+ " after retainAll() operation\n");
		for(String founder : originalSet) {
			System.out.println(founder);
		}

		// Iterating using enhanced for-loop
		System.out.println("\n\n\nIterating retainable set\n");
		for(String founder : retainableSet) {
			System.out.println(founder);
		}
	}
}

Output:

Iterating original set

Shiv Nadar
Sundar Pichai
Satya Nadella
Shantanu Narayen

Iterating original set, after retainAll() operation

Sundar Pichai
Shantanu Narayen

Iterating retainable set

Sundar Pichai
Shantanu Narayen
Narayan Murthy

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to check whether particular element is present in HashSet ?
Java - How to delete an element and delete all elements of HashSet ?