Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

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

I have a 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);

And a Set Set

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

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...