Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

retainAll()

Example

Eliminate items from a list that are not part of a specified collection.

import java.util.LinkedList;
public class Main {
 public static void main(String[] args) {
    LinkedList<String> cars = new LinkedList<String>();
    cars.add("Volvo");
    cars.add("BMW");
   cars.add("Ford");
    cars.add("Mazda");
    cars.add("Toyota");
    LinkedList<String> valid = new LinkedList<String>();
    valid.add("Volvo");
    valid.add("Ford");
    valid.add("Mazda");
    cars.retainAll(valid);
    System.out.println(cars);
  }
}

The retainAll() method removes all items from a list that are not contained in a specified collection.


Syntax

public boolean retainAll(Collection items)

Parameter Values

Parameter

Description

Items

Mandatory: A collection containing the items to retain in the list, removing all others.

Technical Details

Returns:

True if the list was altered; otherwise, false.

Throws:

NullPointerException occurs if the collection is null.