commentから(もっとhere参照):私は、左のどの項目のみに知っていただきたいと思います
ただけ共通で(同様の違いをマッピングする)権利、
使用上のremoveAll()
および[retainAll()][3]
。
例:
Set<Integer> set1 = new HashSet<>(Arrays.asList(1,3,5,7,9));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3,4,5,6,7));
Set<Integer> onlyIn1 = new HashSet<>(set1);
onlyIn1.removeAll(set2);
Set<Integer> onlyIn2 = new HashSet<>(set2);
onlyIn2.removeAll(set1);
Set<Integer> inBoth = new HashSet<>(set1);
inBoth.retainAll(set2);
System.out.println("set1: " + set1);
System.out.println("set2: " + set2);
System.out.println("onlyIn1: " + onlyIn1);
System.out.println("onlyIn2: " + onlyIn2);
System.out.println("inBoth : " + inBoth);
出力さて
set1: [1, 3, 5, 7, 9]
set2: [3, 4, 5, 6, 7]
onlyIn1: [1, 9]
onlyIn2: [4, 6]
inBoth : [3, 5, 7]
、あなたはすべての値を知りたいと、彼らが発見された場合は、あなたがこの(Javaの8)を行うことができる場合:
Set<Integer> setA = new HashSet<>(Arrays.asList(1,3,5,7,9));
Set<Integer> setB = new HashSet<>(Arrays.asList(3,4,5,6,7));
Map<Integer, String> map = new HashMap<>();
for (Integer i : setA)
map.put(i, "In A");
for (Integer i : setB)
map.compute(i, (k, v) -> (v == null ? "In B" : "In Both"));
System.out.println("setA: " + setA);
System.out.println("setB: " + setB);
map.entrySet().stream().forEach(System.out::println);
出力
setA: [1, 3, 5, 7, 9]
setB: [3, 4, 5, 6, 7]
1=In A
3=In Both
4=In B
5=In Both
6=In B
7=In Both
9=In A
使用しない理由https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Sets.html#difference-java.util .Set-java.util.Set-?なぜあなたはセットを地図に強制しようとしていますか? – luk2302
私は左にあるものだけを知っていますが、それは共通です(マップの相違に似ています) – oshai
キーが必要な場合は、なぜマップに変換していますか? Mapは基本的には値を持つSetなので、あなたが言っていることは意味をなさない。 – Andreas