Uncover the Power of retainAll() Method in Java
When working with ArrayLists in Java, managing elements efficiently is crucial. One powerful method that can help you achieve this is retainAll(). In this article, we’ll dive into the world of retainAll() and explore its syntax, parameters, return values, and examples.
What is retainAll() Method?
The retainAll() method is a part of the ArrayList class in Java. It’s used to retain only those elements in the ArrayList that are present in a specified collection. This method is essential when you need to filter out unwanted elements and keep only the common ones.
Syntax and Parameters
The syntax of the retainAll() method is straightforward:
arraylist.retainAll(collection)
Here, arraylist
is an object of the ArrayList class, and collection
is the specified collection that contains the elements to be retained.
Return Value and Exceptions
The retainAll() method returns true
if elements are removed from the ArrayList. However, it can also throw two exceptions:
ClassCastException
: If the class of elements present in the ArrayList is incompatible with the class of elements in the specified collection.NullPointerException
: If the ArrayList contains a null element and the specified collection does not allow null elements.
Example 1: Retaining Common Elements between Two ArrayLists
Let’s create two ArrayLists, languages1
and languages2
, and use the retainAll() method to retain only the common elements.
“`
ArrayList
languages1.add(“Java”);
languages1.add(“Python”);
languages1.add(“C++”);
ArrayList
languages2.add(“Java”);
languages2.add(“C#”);
languages2.add(“Python”);
languages1.retainAll(languages2);
System.out.println(languages1); // Output: [Java, Python]
“`
Example 2: Finding Common Elements between ArrayList and HashSet
In this example, we’ll create an ArrayList numbers
and a HashSet primeNumbers
. We’ll use the retainAll() method to retain only the common elements.
“`
ArrayList
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
HashSet
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
numbers.retainAll(primeNumbers);
System.out.println(numbers); // Output: [2, 3]
“`
By mastering the retainAll() method, you can efficiently manage your ArrayLists and extract valuable insights from your data. Remember, this powerful method is just a few lines of code away!