您可以将 HashMap 的键与集合进行比较吗?

Can you compare the Keys of a HashMap with a Set?

我有一个 Hashmap

 HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
    hashmap.put(0,1);
    hashmap.put(1,1);
    hashmap.put(2,1);
    hashmap.put(3,2);

还有一套

 Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5), Set.of(6, 7, 8));

现在我想将我的 hashmap 与集合进行比较,并输出包含所有 3 个键且值相同的集合。例如,hashmap {0=1, 1=1, 2=1, 3=2} 应该输出集合 (0,1,2)。 我尝试使用 stream():

hashmap.entrySet().stream().filter(e-> e.getValue()==1).map(Map.Entry::getKey).forEach(System.out::println);

但我不知道如何比较它们

 Stream<Set<Integer>> streamsets = set.stream();
  streamsets.forEach(System.out::println);

您应该直播 set 而不是地图:

set.stream().filter(
        // s has to be a subset of the map's keys
        s -> hashmap.keySet().containsAll(s) &&

        // then we look up the associated values
        s.stream().map(hashmap::get)
            .distinct() // only keep distinct values
            .limit(2).count() == 1 // there should only be one distinct value
    ).forEach(System.out::println);