将HashSet的内容与地图进行比较

时间:2019-05-21 21:50:44

标签: java java-8 hashset

我有一个Map和一个HashSet。 目的是对照Map检查Set的内容,如果元素在HashSet中但不在Map中,则将其添加到Map中。

// Map is defined in a class 
private final Map<String, A> sb = new ConcurrentHashMap<>();

public void someMethod() {
    Set<A> hSet = new HashSet<>();
    for (A a : ab){
        hSet.add(a..a...);

        // Check if all elements added to hash Set are there in a Map 
        // if not present, add it to Map 
    }
}

4 个答案:

答案 0 :(得分:2)

如果要搜索地图值:

if(!map.values().contains(a))
   // put a in the map

如果您想查找钥匙

if(!map.containsKey(a))
  // put a in the map

请记住,其中包含调用等于,因此在您的A类中,您必须实现hashCode和equals。

答案 1 :(得分:2)

public static void main(String[] args) {
    Set<String> set = Stream.of("a","b","c","d").collect(Collectors.toSet());
    Map<String, String> map = new HashMap<String, String>();
    map.put("a", "foo");
    map.put("h", "bar");
    map.put("c", "ipsum");

    for (String string : set) {
        if(!map.containsKey(string)) {
            map.put(string,string);
        }
    }
    System.out.println(map);
}

输出

{a=foo, b=b, c=ipsum, d=d, h=bar}

答案 2 :(得分:1)

for (String element : hSet) {
    if (!sb.containsKey(element)) {
        sb.put(element, A);
    }
}

答案 3 :(得分:0)

以下也可以解决:

private final Map<String, A> sb = new ConcurrentHashMap<>();

public void someMethod() {
        Set<String> set = new HashSet<>();
        set.stream().filter(word -> !sb.containsKey(word))
                .forEach(word -> sb.put(word, correspondingValueOfTypeA));
    }