Set Implementation in Java


import java.util.HashSet;
import java.util.Set;

public class SetImplementation {
 public static void main(String[] args) {
  Set<String> hashSet1 = new HashSet<String>();
  hashSet1.add("A");
  hashSet1.add("B");
  hashSet1.add("C");
  hashSet1.add("D");

  Set<String> hashSet2 = new HashSet<String>();
  hashSet2.add("A");
  hashSet2.add("E");
  hashSet2.add("F");
  hashSet2.add("G");

  System.out.println("Hashset1 :" + hashSet1);
  System.out.println("Hashset2 :" + hashSet2);
  // Union of Two sets
  hashSet1.addAll(hashSet2);
  System.out.println("Union :" + hashSet1);

  // Intersection of set
  hashSet1.removeAll(hashSet2);
  System.out.println("Intersection :" + hashSet1);

  // Set difference
  hashSet1.retainAll(hashSet2);
  System.out.println("Set difference :" + hashSet1);
 }

}


Output:
 
Union :[D, E, F, G, A, B, C, H, I]
Intersection :[D, B, C]
Set Difference : [A]
SHARE

About Unknown

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment