如何将 HashMap 的键与集合进行比较?
How to Compare a Key of a HashMap with a Set?
我有一个 HashMap
:
HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
还有一个 Set
的 Set
个:
Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));
我想检查 HashMap
的 3 个键是否包含 Set
的 3 个元素,如果是,请检查值是否相等。
例如:
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;
是否有 stream()
的可能解决方案?
首先,我会检查地图条目并确保它们都与键匹配,因为无论设置如何都可以检查。您可以通过流式传输条目并使用 allMatch
来实现此目的。然后,您可以流过这些集合,并检查它们中的每一个是否与地图大小相同并且所有键都匹配:
return hashMap.entrySet()
.stream()
.allMatch(e -> e.getKey().equals(e.getValue())) &&
set.stream()
.anyMatch(s -> s.size() == hashMap.size() && s.containsAll(hashMap.keySet()));
试试这个。
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);
}
和
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));
输出:
{0=1, 1=1, 2=1} : true
{12=2, 4=2, 5=2} : false
我有一个 HashMap
:
HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
还有一个 Set
的 Set
个:
Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));
我想检查 HashMap
的 3 个键是否包含 Set
的 3 个元素,如果是,请检查值是否相等。
例如:
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;
是否有 stream()
的可能解决方案?
首先,我会检查地图条目并确保它们都与键匹配,因为无论设置如何都可以检查。您可以通过流式传输条目并使用 allMatch
来实现此目的。然后,您可以流过这些集合,并检查它们中的每一个是否与地图大小相同并且所有键都匹配:
return hashMap.entrySet()
.stream()
.allMatch(e -> e.getKey().equals(e.getValue())) &&
set.stream()
.anyMatch(s -> s.size() == hashMap.size() && s.containsAll(hashMap.keySet()));
试试这个。
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);
}
和
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));
输出:
{0=1, 1=1, 2=1} : true
{12=2, 4=2, 5=2} : false