chris01
chris01

Reputation: 12331

Compare all members of a list

Lets say I have a list of objects. How can I compare all of the lists members in an elegant way?

My idea is to check 2 members and iterate to the next one. If 1st equals 2nd and 2nd equals 3rd ... then all are equal by transitivity.

But I think there should be are better way.

List<String> lst = new ArrayList<>();
lst.add("a");
lst.add("b");

String last = null;
boolean ok = true;
for (String s : lst) {
    if (last != null && !last.equals(s)) {
        ok = false;
        break;
    }

    last = s; 
}

EDIT

My question is not about finding a better algorithm. I am looking for a built-in function that does it for me so I do not need to do the algorithm myself.

Upvotes: 1

Views: 626

Answers (2)

CliveLewis
CliveLewis

Reputation: 74

There are many ways to achieve what you need. This post provides different examples using the basic loops, collections API, Streams and Third-Party libraries - https://www.baeldung.com/java-list-all-equal

Since you asked for the most elegant way, here are some examples that I considered such:

Use HashSet - If we convert a List to a HashSet and the resulting size is less than or equal to 1, then we know that all elements in the list are equal:

public boolean verifyAllEqualUsingHashSet(List<String> list) {
    return new HashSet<String>(list).size() <= 1;
}

Java 8+ Streams - Count the distinct elements. If result is <= 1, then all values are equal.

public boolean verifyAllEqualUsingStream(List<String> list) {
    return list.stream()
      .distinct()
      .count() <= 1;
}

Collections API - frequency method returns the number of elements in a Collection c matching an Object. So, if the frequency result is equal to the size of the list, we know that all the elements are equal:

public boolean verifyAllEqualUsingFrequency(List<String> list) {
    return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size();
}

Upvotes: 1

Sergey Zh.
Sergey Zh.

Reputation: 437

Compare all elements with the first element. It turns out N-1 operations, it can not be less.

Upvotes: 1

Related Questions