How to check if items in a list are identical?

Is there a cleaner way in Java to confirm that all elements in a List identical?

 boolean elementsAreIdentical() { return new HashSet<O>(list).size() == 1; } 

Under β€œclean,” I wonder if we can do this without creating a completely new object? Depending on the size of the service data may be significant.

+4
source share
3 answers
 if (Collections.frequency(list, list.get(0)) == list.size()) { /* duplicates */ } 

... for a list that is not empty. Otherwise,

 final int n = list.size(); if (n == 0 || Collections.frequency(list, list.get(0)) == n) { /* duplicates */ } 

See the Collections.frequency specification. It will be cheaper than your approach, as well as others, for example. Collections.nCopies(list.get(0), list.size()).equals(list)

+6
source

This is a rather expensive way to achieve the result - in the case of large data structures, you will face significant overhead both in the memory area and in the processor cycle. My first recommendation was to control this when creating the list.

0
source

This is a bit verbose, but it has O(n) and O(1) complexity of time and space, respectively, although it will stop when the first non-identical element is found:

 public static <T> boolean elementsAreIdentical(List<T> l) { if (!l.isEmpty()) { Iterator<T> it = l.iterator(); T unique = it.next(); while (it.hasNext()) { if (!it.next().equals(unique)) { return false; } } } return true; } 
0
source

All Articles