I have a HashMap
:
HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
And a Set
of Set
s:
Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));
I want to check if 3 of the Keys of the HashMap
contain 3 Elements of the Set
and if so check if the values are equal.
for example :
hashMap.put(0,1);
hashMap.put(1,1);
hashMap.put(2,1);
return true;
hashMap.put(4,2);
hashMap.put(5,2);
hashMap.put(12,2);
return false;
is there a possible solution with stream()
?
First, I'd go over the map entries and make sure they all match the keys, since this can be checked regardless of the set. You can achieve this by streaming the entries and using allMatch
. Then, you can stream over the sets, and for each of them check it's the same size of the map and all the keys match:
return hashMap.entrySet()
.stream()
.allMatch(e -> e.getKey().equals(e.getValue())) &&
set.stream()
.anyMatch(s -> s.size() == hashMap.size() && s.containsAll(hashMap.keySet()));
Try this.
static boolean test(HashMap<Integer, Integer> hashMap, Set<Set<Integer>> set) {
return set.stream()
.anyMatch(s -> hashMap.keySet().containsAll(s) &&
s.stream().map(k -> hashMap.get(k)).distinct().count() == 1);
}
and
Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));
HashMap<Integer, Integer> hashMap1 = new HashMap<>(Map.of(0, 1, 1, 1, 2, 1));
System.out.println(hashMap1 + " : " + test(hashMap1, set));
HashMap<Integer, Integer> hashMap2 = new HashMap<>(Map.of(4, 2, 5, 2, 12, 2));
System.out.println(hashMap2 + " : " + test(hashMap2, set));
output:
{0=1, 1=1, 2=1} : true
{12=2, 4=2, 5=2} : false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.