Java所有确定元素在列表中都是相同的
我试图确定列表中的所有元素是否相同。 例如: 我知道hashset可能会有帮助,但我不知道如何用java编写 这是我试过的一个,但不起作用:Java所有确定元素在列表中都是相同的,java,list,hashset,brute-force,Java,List,Hashset,Brute Force,我试图确定列表中的所有元素是否相同。 例如: 我知道hashset可能会有帮助,但我不知道如何用java编写 这是我试过的一个,但不起作用: public static boolean allElementsTheSame(List<String> templist) { boolean flag = true; String first = templist.get(0); for (int i = 1; i< templist.size() &
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;
}
公共静态布尔等位基因相同(列表模板)
{
布尔标志=真;
String first=templast.get(0);
对于(int i=1;i
使用流API(Java 8+)
使用集合
:
boolean allEqual = new HashSet<String>(tempList).size() <= 1;
boolean allEqual = true;
for (String s : list) {
if(!s.equals(list.get(0)))
allEqual = false;
}
OP代码问题
您的代码有两个问题:
- 因为您正在比较
s,所以应该使用字符串
而不是!templast.get(i).equals(first)
=代码>
- 您有
而应为返回true
返回标志代码>
标志
:
String first = templist.get(0);
for (int i = 1; i < templist.size(); i++) {
if(!templist.get(i).equals(first))
return false;
}
return true;
这是
Stream.allMatch()方法的一个很好的用例:
布尔allMatch(谓词)
返回此流的所有元素是否与提供的谓词匹配
您甚至可以将您的方法设置为泛型,以便它可以用于任何类型的列表:
static boolean allElementsTheSame(List<?> templist) {
return templist.stream().allMatch(e -> e.equals(templist.get(0)));
}
静态布尔等位基因相同(列表模板){
返回templast.stream().allMatch(e->e.equals(templast.get(0));
}
列表中值的频率将与列表的大小相同
boolean allEqual=Collections.frequency(templast,list.get(0))==templast.size()
我建议您向我们展示您已经尝试过的Java代码。如果所有元素都相同,则它们必须都等于第一个元素(除非list为空)。。。只需迭代并检查它,您需要返回标志至少在您的代码中有code>。您当前总是在最后一行返回true。@PM77-1,对于(1,2,3,4,5)
的列表,限制(2)
将确保它在(1,2)
之后提前终止。我理解这一点。问题是count()
的成本是否足以超过额外操作的开销。对于具有许多独特元素的大型列表,这会产生不同。例如,考虑<代码>(“000000000 1”,“00000000 2”,…,“999999999”)< /代码>。查看前两个元素明显更快,然后必须计算总共有多少个唯一元素。不幸的是,使用HashSet
的allSame
方法的解决方案被删除了。。。尽管如此,使用1_000_000字符串和1.)第3个值进行的少量(非代表性)性能测试与所有其他测试不同:对于循环:0ms,设置:31ms,流:47ms,2.)所有值相等:对于循环:18ms,设置:32ms,流:85ms,因此set
解决方案不是最差的;被接受的流
解决方案似乎是性能最低的解决方案,也是普通的for循环赢款解决方案;结论:衡量性能总是好的…@tomse,JVM上的微观基准测试是出了名的困难。你的测量值低于十分之一秒这一事实告诉我这些数据不是很可靠。为什么整个if
-语句都是这样?我相信,只要第二份回执就行了。是的,你说得对。我试图阻止get(0)
上出现IndexOutOfBoundsException
,但我发现这不会发生,因为当列表为空时,get(0)
不会执行。我更新了答案。谢谢你注意到了。
boolean allEqual = true;
for (String s : list) {
if(!s.equals(list.get(0)))
allEqual = false;
}
String first = templist.get(0);
for (int i = 1; i < templist.size(); i++) {
if(!templist.get(i).equals(first))
return false;
}
return true;
String first = templist.get(0);
for (String s : templist) {
if(!s.equals(first))
return false;
}
return true;
static boolean allElementsTheSame(List<?> templist) {
return templist.stream().allMatch(e -> e.equals(templist.get(0)));
}