집합과 관련된 것을 쉽게 처리하기 위해 만든 것으로 HashSet, TreeSet, LInkedHashSet 등이 있다.
중복을 허용하지 않고 순서가 없는 것이 특징이다.
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> intersection = new HashSet<>(s1); // s1으로 intersection 생성
intersection.retainAll(s2); // 교집합 수행
System.out.println(intersection); // [4, 5, 6] 출력
}
}
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> union = new HashSet<>(s1); // s1으로 union 생성
union.addAll(s2); // 합집합 수행
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8, 9] 출력
}
}
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
HashSet<Integer> substract = new HashSet<>(s1); // s1으로 substract 생성
substract.removeAll(s2); // 차집합 수행
System.out.println(substract); // [1, 2, 3] 출력
}
}
//add
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Jump");
set.add("To");
set.add("Java");
System.out.println(set); // [Java, To, Jump] 출력
}
}
//addAll
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Jump");
set.addAll(Arrays.asList("To", "Java"));
System.out.println(set); // [Java, To, Jump] 출력
}
}
//remove
import java.util.Arrays;
import java.util.HashSet;
public class Sample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(Arrays.asList("Jump", "To", "Java"));
set.remove("To");
System.out.println(set); // [Java, Jump] 출력
}
}