在 Java 中,如何测试数组是否包含相同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21170608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, how can I test if an Array contains the same value?
提问by ternes3
I'm looking for a method to detect if all objects within an array(list) are the same. e. g:
我正在寻找一种方法来检测数组(列表)中的所有对象是否相同。e. G:
arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same
Thanks for help
感谢帮助
采纳答案by Justin Niessner
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;
}
Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.
请随时更正任何语法错误。我担心我的 Java-fu 今天可能会缺乏。
回答by peter.petrov
If your list is empty return true. If not, loop through it and check if all elements are equal to the element at index 0. If so, return true, otherwise return false.
如果您的列表为空,则返回 true。如果不是,则循环遍历它并检查是否所有元素都等于索引 0 处的元素。如果是,则返回 true,否则返回 false。
回答by Petr Mensik
public boolean containsSameValues(int[] array) {
if(array.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int first = array[0];
for(int i=0;i<array.length;i++) {
if(array[i] != first) {
return false;
}
}
return true;
}
回答by Dawood ibn Kareem
if( new HashSet<String>(Arrays.asList(yourArray)).size() == 1 ){
// All the elements are the same
}
回答by Alexis C.
Java 8 solution :
Java 8 解决方案:
boolean match = Arrays.stream(arr).allMatch(s -> s.equals(arr[0]));
Same logic for lists :
列表的相同逻辑:
boolean match = list.stream().allMatch(s -> s.equals(list.get(0)));
如果
null
null
数组中只有或任何值(导致 a NullPointerException
NullPointerException
),它就会变得非常复杂。所以可能的解决方法是:Using
Predicate.isEqual
, it uses the static methodequals
from theObjects
class and it will do the null check for you before calling equals on the first argument.boolean match = Arrays.stream(arr).allMatch(Predicate.isEqual(arr[0]));
boolean match = Arrays.stream(arr).allMatch(s -> Objects.equals(arr[0], s));
Using
distinct()
andcount()
:boolean match = Arrays.stream(arr).distinct().count() == 1;
that can be improved into
Arrays.stream(arr).distinct().limit(2).count() == 1;
as there is no need to check the all pipeline's content if you already find 2 distinct elements.
使用
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 个不同的元素,则无需检查所有管道的内容。
回答by JBojan
boolean containsAllValues=false;
boolean t=false;
int isto=0;
for(int k=0;k<arraylist1.size();k++){
for(int n=0;n<arraylist2.size();n++){
if(arraylist1.get(k).equals(arraylist2.get(n))){
t=true;
}
}
if(t){
isto++;
}else{
isto=0;
break;
}
}
if(isto!=0){
containsAllValues=true;
}
With this you can check if arraylist2 contains values from arraylist1.
有了这个,您可以检查 arraylist2 是否包含来自 arraylist1 的值。
回答by uoftcode
You can sort the array and then use the Array equals method:
您可以对数组进行排序,然后使用 Array equals 方法:
public boolean equalArrays(int []f ,int [] g){
Arrays.sort(f);
Arrays.sort(g);
if (Arrays.equals(f, g))
return true;
return false;
}
To test it out:
测试一下:
int [] h={1,1,0,1};
int [] t={1,1,1,0};
System.out.println(cc.equalArrays(h,t));
回答by Priidu Neemre
For Java 8, Alexis C's solution is probably the best. However, if you're stuck with <= Java 7 and don't think David Wallace's approach is expressive enough, you could also try this:
对于 Java 8,Alexis C 的解决方案可能是最好的。但是,如果您坚持使用 <= Java 7 并且认为 David Wallace 的方法不够富有表现力,您也可以试试这个:
boolean result = Collections.frequency(yourList, "1") == yourList.size();
Basically what this does is that it checks whether the number of elements in your list equal to "1" matches the total number of elements in the list. Pretty straightforward.
基本上它的作用是检查列表中等于“1”的元素数是否与列表中的元素总数匹配。很简单。
By the way -- this is pure Java Collections API
, and I believe Collection.frequency(..)
has been there since at least JDK 1.5. See the javadocsfor more information.
顺便说一句——这是纯 Java Collections API
,我相信Collection.frequency(..)
至少从 JDK 1.5 开始就已经存在了。有关更多信息,请参阅javadoc。
EDIT: Here's a quick fiddleif you want to take this for a test drive.
编辑:如果你想试驾,这里有一个快速的小提琴。