Java Collection Tutorial - Java Set.retainAll(Collection <?> c)








Syntax

Set.retainAll(Collection <?> c) has the following syntax.

boolean retainAll(Collection <?> c)

Example

In the following code shows how to use Set.retainAll(Collection <?> c) method.

//w  ww  . j  a v  a  2 s  .c o  m
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {

    // Create two sets.
    Set s1 = new HashSet();
    s1.add("A");
    s1.add("B");
    s1.add("C");

    Set s2 = new HashSet();
    s2.add("A");
    s2.add("B");

    Set union = new TreeSet(s1);
    union.addAll(s2); // now contains the union

    print("union", union);

    Set intersect = new TreeSet(s1);
    intersect.retainAll(s2);

    print("intersection", intersect);

  }

  protected static void print(String label, Collection c) {

    System.out.println("--------------" + label + "--------------");

    Iterator it = c.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
  }
}

The code above generates the following result.