Java : 如何比较map keyset和set?
Java : How to compare map keyset with set?
我有一张地图(名为 masterMap
)和一套。
masterMap
包含这些值 - {1537=OK, 1538=OK, 1539=OK, 4003=OK}
Set selectedSet =new HashSet();
selectedSet.add(Integer.parseInt("4003"));
boolean compareMapAndSet=masterMap.keySet().equals(selectedSet);
但是,即使地图中存在 4003,compareMapAndSet
始终是 false
。
比较有什么问题?
equals
比较对象是否相等。它不检查第二组是否是第一组的子集。要获得该功能,您应该使用 containsAll
boolean compareMapAndSet=masterMap.keySet().containsAll(selectedSet);
来自集合 public boolean equals(Object o)
Compares the specified object with this set for equality. Returns true
if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).
注意: 但是在您给出的示例中,您的 selectedSet
没有相同的元素。
我想你想检查 selectedSet
集合中的所有元素是否都是 masterMap.keySet()
的一部分
因为没有搁浅 API 你必须遍历你设置 selectedSet
并在 masterMap.keySet()
中检查它是否存在。像下面的代码:
boolean compareMapAndSet = checkSubSet(masterMap.keySet(), selectedSet);
private static boolean checkSubSet(Set<Integer> keySet, Set<Integer> selectedSet) {
for (Integer integer : selectedSet) {
if (!keySet.contains(integer)) {
return false;
}
}
return true;
}
查看输出 result
我有一张地图(名为 masterMap
)和一套。
masterMap
包含这些值 - {1537=OK, 1538=OK, 1539=OK, 4003=OK}
Set selectedSet =new HashSet();
selectedSet.add(Integer.parseInt("4003"));
boolean compareMapAndSet=masterMap.keySet().equals(selectedSet);
但是,即使地图中存在 4003,compareMapAndSet
始终是 false
。
比较有什么问题?
equals
比较对象是否相等。它不检查第二组是否是第一组的子集。要获得该功能,您应该使用 containsAll
boolean compareMapAndSet=masterMap.keySet().containsAll(selectedSet);
来自集合 public boolean equals(Object o)
Compares the specified object with this set for equality. Returns
true
if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).
注意: 但是在您给出的示例中,您的 selectedSet
没有相同的元素。
我想你想检查 selectedSet
集合中的所有元素是否都是 masterMap.keySet()
因为没有搁浅 API 你必须遍历你设置 selectedSet
并在 masterMap.keySet()
中检查它是否存在。像下面的代码:
boolean compareMapAndSet = checkSubSet(masterMap.keySet(), selectedSet);
private static boolean checkSubSet(Set<Integer> keySet, Set<Integer> selectedSet) {
for (Integer integer : selectedSet) {
if (!keySet.contains(integer)) {
return false;
}
}
return true;
}
查看输出 result