检查地图中的所有值是否相等 [英] Check if all values in a map are equal
本文介绍了检查地图中的所有值是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查地图中的所有值是否相等。我有一个方法来执行这个任务,但是想使用一个库或本地方法。限制:Java 5 + Apache Commons库。
I need to check if all values in a map are equal. I have a method to perform this task but would like to use a library or native methods. Limitations: Java 5 + Apache Commons libraries.
public static boolean isUnique(Map<Dboid,?> aMap){
boolean isUnique = true;
Object currValue = null;
int iteration = 0;
Iterator<?> it = aMap.entrySet().iterator();
while(it.hasNext() && isUnique){
iteration++;
Object value = it.next();
if(iteration > 1){
if (value != null && currValue == null ||
value == null && currValue != null ||
value != null && currValue != null & !value.equals(currValue)) {
isUnique = false;
}
}
currValue = value;
}
return isUnique;
}
推荐答案
:
Set<String> values = new HashSet<String>(aMap.values());
boolean isUnique = values.size() == 1;
这篇关于检查地图中的所有值是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文