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) |
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
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!