2017-03-21 3 views
0

私はセットを持っていて、後でguavaのMaps.difference()で使用するためにマップに変換したいと思います。私は違いのキーだけを気にします。
は、このバージョンを思い付いた:セットをマップに変換する方法

private <T> Map<T, T> toMap(Set<T> set) { 
    return set.stream().collect(Collectors.toMap(Function.identity(), Function.identity())); 
} 

しかし、私は通常、セットはマップのバッキングフィールドを持っていることを知っています。私は、私は多分、私が何とかこのフィールドのビューを取得することができます思っキーを必要とするので

public static <E> Set<E> newConcurrentHashSet() { 
    return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>()); 
} 

:これは私がマップを作成するために使用する方法です。何か案が?下図のようにあなたがMap(同じキーとSetの要素から取られた値)にSetに変換することができます

+2

使用しない理由https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Sets.html#difference-java.util .Set-java.util.Set-?なぜあなたはセットを地図に強制しようとしていますか? – luk2302

+0

私は左にあるものだけを知っていますが、それは共通です(マップの相違に似ています) – oshai

+1

キーが必要な場合は、なぜマップに変換していますか? Mapは基本的には値を持つSetなので、あなたが言っていることは意味をなさない。 – Andreas

答えて

2

private <T> Map<T, T> toMap(Set<T> set) { 
    Map<T, T> map = new ConcurrentHashMap<>(); 
    set.forEach(t -> map.put(t, t));//contains same key and value pair 
    return map; 
} 
0

は同様の答えhereを参照してください。

元のセットが値のセット(元のデータにキーはありません!)であると仮定すると、新しく作成されたマップのキーを指定する必要があります。グアバのMaps.uniqueIndexが役に立ちます(hereを参照)

オリジナルセットがキーのセット(元のデータに値がありません!)を保持したい場合は、新しく作成するデフォルト値または特定の値を指定する必要があります作成された地図。グアバのMaps.toMapが参考になるかもしれません。

1

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 
関連する問題