我正在寻找一种方法来检测数组(列表)中的所有对象是否相同.即 G:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Run Code Online (Sandbox Code Playgroud)
感谢帮助
Ale*_* C. 20
Java 8解决方案:
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Run Code Online (Sandbox Code Playgroud)
列表的逻辑相同:
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
Run Code Online (Sandbox Code Playgroud)
null数组中只有或任何值(导致a NullPointerException),它会非常复杂.所以可能的解决方法是:
使用Predicate.isEqual,它采用静态方法equals从Objects类,它会做空校验你的第一个参数调用平等之前.
boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
使用 distinct()和count():
boolean match = Arrays.stream(arr).distinct().count() == 1;
可以改进,Arrays.stream(arr).distinct().limit(2).count() == 1;因为如果您已经找到2个不同的元素,则无需检查所有管道的内容.
Jus*_*ner 11
public static boolean AreAllSame(String[] array)
{
boolean isFirstElementNull = array[0] == null;
for(int i = 1; i < array.length; i++)
{
if(isFirstElementNull)
if(array[i] != null) return false;
else
if(!array[0].equals(array[i])) return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
请随意纠正任何语法错误.我担心我的Java-fu今天可能缺乏.
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
Run Code Online (Sandbox Code Playgroud)