James Leonard
James Leonard

Reputation: 3763

When given a list, how to check if elements are equal, or not

Say, you're given a List<KVPair>, where each KVPair has a String key, String Value and .equals() method that does things right.

How would you confirm that each of the elements in the list is like the other, or see if at least one is not?

In other words, if we have

KVPair kvp1 = new KVPAir("key", "value");
KVPair kvp2 = new KVPAir("key", "value");

List<KVPair> l = new ArrayList<KVPair>();
l.add(kvp1);
l.add(kvp2);

The one approach i can think of is, sort the list first and iterate until next is not like previous.

Is there a simpler, cleaner way to find the same?

Upvotes: 4

Views: 3599

Answers (3)

Matthew
Matthew

Reputation: 11387

Using java streams:

list.stream().distinct().count() == 1

Upvotes: 1

James Raitsev
James Raitsev

Reputation: 96531

Here is a generic solution:

Don't forget to do the empty check. First time you add element to the set, it will always be added

public static boolean isListOfSameElements(List<? extends Object> l) {
    Set<Object> set = new HashSet<Object>(l.size());
    for (Object o : l) {
        if (set.isEmpty()) {
            set.add(o);
        } else {
            if (set.add(o)) {
                return false;
            }
        }
    }
    return true;
}

Upvotes: 3

Thilo
Thilo

Reputation: 262834

If hashCode() is also implemented properly, you can add them all into a HashSet and see if you get duplicates:

 Set<KVPair> set = new HashSet<KVPair>(l.size());
 for (KVPair p: l){
   if (!set.add(p))
      // you have a duplicate
 }

or even (a bit wasteful)

Set<KVPair> set = new HashSet<KVPair)(l);
if (l.size() != set.size())
   // you have a duplicate
if (set.size() < 2)
   // all elements are equal

Upvotes: 3

Related Questions