Java 列表中的所有确定元素都相同

Java all determine elements are same in a list

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

(10,10,10,10,10) --> true
(10,10,20,30,30) --> false

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

这是我试过的,但没有用:

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);

使用 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 代码有问题

您的代码有两个问题:

  • 由于您要比较 String,因此您应该使用 !templist.get(i).equals(first) 而不是 !=

  • 你有 return true; 而它应该是 return flag;

除此之外,您的算法是合理的,但您可以通过以下方式在没有 flag 的情况下逃脱:

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;

这是 Stream.allMatch() 方法的一个很好的用例:

boolean allMatch(Predicate predicate)

Returns whether all elements of this stream match the provided predicate.

您甚至可以使您的方法通用,因此它可以与任何类型的列表一起使用:

static boolean allElementsTheSame(List<?> templist) {
    return templist.stream().allMatch(e -> e.equals(templist.get(0)));
}

值在列表中出现的频率与列表的大小相同。

boolean allEqual = Collections.frequency(templist, list.get(0)) == templist.size()