This post will discuss how to check if all items in a List are identical in Java.

1. Using Stream.distinct() method

The idea is to get a sequential stream over the elements in the list and select the distinct elements from the stream using the distinct() method. If all elements in a List are identical, then the count of elements in this stream should be exactly 1.

Download  Run Code

 
Note that the distinct() method compare elements according to Object.equals(Object) method. Therefore, your class should override equals() and hashCode() methods to test equality.

2. Using Stream.allMatch() method

The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same. Note the additional check in the code to handle an empty list.

Download  Run Code

3. Using Set

The most widely used solution to check for identical elements in a list involves converting the list into a set and then checking if the size of the set is 1 or not. This works since the Set data structure silently discards duplicates.

Download  Run Code

4. Using Collections.frequency() method

Finally, you can get the count of any element in the list using the Collections.frequency() method. If its frequency is equal to the number of elements in the list, then we can say that the list has all identical elements.

Download  Run Code

That’s all about checking if all items in a List are identical in Java.