Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...