Java都确定列表中的元素相同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29288568/
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
Java all determine elements are same in a list
提问by Colin Zhong
I am trying to determine to see if all elements in a list are same. such as:
我试图确定列表中的所有元素是否都相同。如:
(10,10,10,10,10) --> true
(10,10,20,30,30) --> false
I know hashset might be helpful, but i don't know how to write in java.
我知道 hashset 可能会有所帮助,但我不知道如何用 java 编写。
this is the one I've tried, but didn't work:
这是我试过的,但没有奏效:
public static boolean allElementsTheSame(List<String> templist)
{
boolean flag = true;
String first = templist.get(0);
for (int i = 1; i< templist.size() && flag; i++)
{
if(templist.get(i) != first) flag = false;
}
return true;
}
采纳答案by aioobe
Using the Stream API (Java 8+)
使用 Stream API (Java 8+)
boolean allEqual = list.stream().distinct().limit(2).count() <= 1
or
或者
boolean allEqual = list.isEmpty() || list.stream().allMatch(list.get(0)::equals);
Using a Set
:
使用Set
:
boolean allEqual = new HashSet<String>(tempList).size() <= 1;
Using a loop:
使用循环:
boolean allEqual = true;
for (String s : list) {
if(!s.equals(list.get(0)))
allEqual = false;
}
Issues with OP's code
OP 代码的问题
Two issues with your code:
您的代码有两个问题:
Since you're comparing
String
s you should use!templist.get(i).equals(first)
instead of!=
.You have
return true;
while it should bereturn flag;
由于您正在比较
String
s,因此您应该使用!templist.get(i).equals(first)
而不是!=
.你
return true;
应该有时间return flag;
Apart from that, your algorithm is sound, but you could get away without the flag
by doing:
除此之外,您的算法是合理的,但您可以通过以下方式逃脱flag
:
String first = templist.get(0);
for (int i = 1; i < templist.size(); i++) {
if(!templist.get(i).equals(first))
return false;
}
return true;
Or even
甚至
String first = templist.get(0);
for (String s : templist) {
if(!s.equals(first))
return false;
}
return true;
回答by Anderson Vieira
This is a great use case for the Stream.allMatch()
method:
这是该Stream.allMatch()
方法的一个很好的用例:
boolean allMatch(Predicate predicate)
Returns whether all elements of this stream match the provided predicate.
boolean allMatch(谓词谓词)
返回此流的所有元素是否与提供的谓词匹配。
You can even make your method generic, so it can be used with lists of any type:
您甚至可以使您的方法通用,因此它可以与任何类型的列表一起使用:
static boolean allElementsTheSame(List<?> templist) {
return templist.stream().allMatch(e -> e.equals(templist.get(0)));
}
回答by darrenp
The frequency of a value in a list will be the same as the size of the list.
列表中某个值的频率将与列表的大小相同。
boolean allEqual = Collections.frequency(templist, list.get(0)) == templist.size()
boolean allEqual = Collections.frequency(templist, list.get(0)) == templist.size()