1. 개요
두개의 Set을 이용하여 교집합, 차집합, 합집합을 구하는 로직이다.
2. 코드
package io.sarc;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ArraySet {
public static void main(String[] args) {
String[] a = { "apple", "banana", "xylophone" };
String[] b = { "banana", "carrot", "dog", "xray", "xylophone" };
Set<String> setA = new HashSet<>(Arrays.asList(a));
Set<String> setB = new HashSet<>(Arrays.asList(b));
ArraySet arraySet = new ArraySet();
arraySet.retainAll(setA, setB);
arraySet.removeAll(setA, setB);
arraySet.addAll(setA, setB);
}
private void retainAll(Set<String> a, Set<String> b) {
Set<String> copyA = new HashSet<>();
copyA.addAll(a);
copyA.retainAll(b);
System.out.println(copyA);
}
private void removeAll(Set<String> a, Set<String> b) {
Set<String> copyA = new HashSet<>();
copyA.addAll(a);
copyA.removeAll(b);
System.out.println(copyA);
}
private void addAll(Set<String> a, Set<String> b) {
Set<String> copyA = new HashSet<>();
copyA.addAll(a);
copyA.addAll(b);
System.out.println(copyA);
}
}