This post will discuss how to determine if a list contains the same elements in Java.

1. Using Stream API

The introduction of Stream API with Java 8 has made this task very easy. The idea is to filter out the duplicate elements and get the count of distinct elements in the list using the Stream.distinct() method. If the count is less than or equal to 1, then all elements in the list must be equal. For example:

Download  Run Code

 
This is a functional and concise way to check if all elements are equal, as it allows expressing the logic of iteration in a single line of code. Another option is to use the Stream.allMatch() method to check if all elements match a supplied predicate. To determine if all elements are the same, the predicate can be a lambda expression that compares each element of the list with the first. For example:

Download  Run Code

2. Using a HashSet

We can use the no-duplicate property of the Set interface to validate if all elements of a list are the same. The idea is to use a HashSet to store the distinct elements of the list and check its size. Since a HashSet contains only unique elements, so if its size is less than or equal to 1, then all elements in the list must be equal. This is a more concise and readable way to check if all elements are equal, but uses extra space.

Download  Run Code

3. Using Collections.frequency() method

Another option is to use the Collections.frequency() method to count the frequency of any single element in the list. This method returns the number of times an element appears in a list, so if its result is equal to the size of the list, then all elements in the list must be equal. This solution runs in linear time, without any extra space. For example:

Download  Run Code

4. Using for loop

Finally, we can use a for loop to compare each element with the first element of the list. This is a simple and straightforward way to check if all elements are equal, but it may not be very intuitive or readable. For example:

Download  Run Code

That’s all about determining if a list contains the same elements in Java.