Java HashSet Interaction/Union/Difference

Description

Java HashSet Interaction/Union/Difference

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

public class Main {

  public static void main(String[] args) {
  
    Set<String> set1 = new HashSet<>();
    Set<String> set2 = new HashSet<>();
    set1.add("CSS");
    set1.add("HTML");
    set1.add("Java");
    set1.add("SQL");
    set1.add("Javascript");
    set2.add("CSS");
    set2.add("SQL");
    set2.add("HTML");
    set2.add("C++");
    set2.add("SQL");
    //w w w  .  ja  v a 2  s.c  o m
    Set<String> setInteraction = interaction(set1, set2);
    Set<String> setUnion = union(set1, set2);
    Set<String> setDifference = difference(set1, set2);
    
    System.out.println("Interaction:");
    for (String string : setInteraction) {
      System.out.println(string);
    }
    System.out.println("\nUnion:");
    for (String string : setUnion) {
      System.out.println(string);
    }
    System.out.println("\nDifference:");
    for (String string : setDifference) {
      System.out.println(string);
    }
  }

  private static Set<String> difference(Set<String> set1, Set<String> set2) {
    Set<String> set = new HashSet<>();
    for (String string : set1) {
      if (!set2.contains(string)){
        set.add(string);
      }
    }
    for (String string : set2) {
      if (!set1.contains(string)){
        set.add(string);
      }
    }
    return set;
  }

  private static Set<String> union(Set<String> set1, Set<String> set2) {
    Set<String> set = new HashSet<>(set1);
    for (String string : set2) {
      set.add(string);
    }
    
    return set;
  }

  private static Set<String> interaction(Set<String> set1, Set<String> set2) {
    Set<String> set = new HashSet<>();
    for (String string : set1) {
      if (set2.contains(string)){
        set.add(string);
      }
    }
    return set;
  }
}



PreviousNext

Related