Set: retainAll(Collection c) : Set « java.util « Java by API






Set: retainAll(Collection c)

 
/*
--------------union--------------
A
B
C
--------------intersection--------------
A
B*/
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class MainClass {
  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());
    }
  }
}

           
         
  








Related examples in the same category

1.Set: add(String e)
2.Set: addAll(Collection c)
3.Set: clear()
4.Set: clone()
5.Set: contains(Object o)
6.Set: containsAll(Collection c)
7.Set: equals(Object o)
8.Set: isEmpty()
9.Set: iterator()
10.Set: remove(Object o)
11.Set: removeAll(Collection c)
12.Set: size()
13.Set: toArray()
14.Set: toArray(String[] a)