Java所有确定元素在列表中是相同的 [英] Java all determine elements are same in a list

查看:148
本文介绍了Java所有确定元素在列表中是相同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确定列表中的所有元素是否相同。
如:

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

我知道hashset可能会有所帮助,但我不知道如何用java编写。

I know hashset might be helpful, but i don't know how to write in 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;
}


推荐答案

使用流API(Java 8 +)

boolean allEqual = list.stream().distinct().limit(2).count() <= 1

boolean allEqual = list.isEmpty() || list.stream().allMatch(list.get(0)::equals);

使用设置

Using a Set:

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你应该使用!templist.get(i).equals(first)而不是!=

  • Since you're comparing Strings you should use !templist.get(i).equals(first) instead of !=.

你有返回true; 虽然应该返回标志;

除此之外,你的算法是合理的,但是你可以在没有标志的情况下离开:

Apart from that, your algorithm is sound, but you could get away without the flag by doing:

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;

这篇关于Java所有确定元素在列表中是相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆