Java all determine elements are same in a list

前端 未结 3 580
再見小時候
再見小時候 2020-12-09 02:15

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 k

相关标签:
3条回答
  • 2020-12-09 02:47

    Using the 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:

    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

    Two issues with your code:

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

    • You have return true; while it should be return flag;

    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;
    

    Or even

    String first = templist.get(0);
    for (String s : templist) {
        if(!s.equals(first))
            return false;
    }
    return true;
    
    0 讨论(0)
  • 2020-12-09 02:48

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

    0 讨论(0)
  • 2020-12-09 02:48

    This is a great use case for the Stream.allMatch() method:

    boolean allMatch(Predicate predicate)

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

    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)));
    }
    
    0 讨论(0)
提交回复
热议问题