你能将 HashMap 的键与 Set 进行比较吗? [英] Can you compare the Keys of a HashMap with a Set?

查看:65
本文介绍了你能将 HashMap 的键与 Set 进行比较吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希图

 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));

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

Now i want to compare my hashmap with the set and output the set which is containing all 3 keys and where the values are the same. e.g the hashmap {0=1, 1=1, 2=1, 3=2} should output the set (0,1,2). I tried to use stream():

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

但我不知道如何比较它们

But i dont know how to compare them with each other

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

推荐答案

您应该流式传输 set 而不是映射:

You should stream set instead of the map:

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);

这篇关于你能将 HashMap 的键与 Set 进行比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆