Java Set intersect

Description

Java Set intersect


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

public class Main {
  public static <T> Set<T> intersect(Set<T> s1, Set<T> s2) {
    Set<T> s1Intersections2 = new HashSet<>(s1);
    s1Intersections2.retainAll(s2);/*  ww  w. j  a v a 2  s. c o m*/
    return s1Intersections2;
  }

  public static void main(String[] args) {
    Set<String> s1 = new HashSet<>();
    s1.add("HTML");
    s1.add("CSS");
    s1.add("XML");

    Set<String> s2 = new HashSet<>();
    s2.add("Java");
    s2.add("XML");
    s2.add("Javascript");
    s2.add("CSS");
    
    System.out.println(s1);
    System.out.println(s2);
    
    Set<String> s3 = intersect(s1, s2);
    
    System.out.println(s3);
  }
}



PreviousNext

Related