List retainAll() Method in Java with Examples

This method is used to retain all the elements present in the collection from the specified collection into the list.

Syntax:

boolean retainAll(Collection c)

Parameters: This method has only argument, collection of which elements are to be retained in the given list.

Returns: This method returns True if elements are retained and list changes.

Below programs show the implementation of this method.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show the implementation of
// retainAll method in list interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a list of type Linkedlist
        List<Integer> l = new LinkedList<>();
        l.add(1);
        l.add(3);
        l.add(5);
        l.add(7);
        l.add(9);
        System.out.println(l);
  
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(3);
        arr.add(5);
        l.retainAll(arr);
  
        System.out.println(l);
    }
}

chevron_right


Output:

[1, 3, 5, 7, 9]
[3, 5]

Program 2: Below is the code to show implementation of list.retainAll() using Linkedlist.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show the implementation of
// retainAll method in list interface
import java.util.*;
public class GfG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Initializing a list of type Linkedlist
        List<String> l = new LinkedList<>();
        l.add("10");
        l.add("30");
        l.add("50");
        l.add("70");
        l.add("90");
        System.out.println(l);
  
        ArrayList<String> arr = new ArrayList<>();
        arr.add("30");
        arr.add("50");
        l.retainAll(arr);
  
        System.out.println(l);
    }
}

chevron_right


Output:

[10, 30, 50, 70, 90]
[30, 50]

Reference:
Oracle Docs



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.