James Leonard James Leonard - 11 days ago 7
Java Question

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?

JAM JAM
Answer

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;
}
Comments