James Leonard James Leonard - 1 year ago 79
Java Question

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

Say, you're given a

, where each
has a
String key
String Value
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>();

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?

Answer Source

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()) {
        } else {
            if (set.add(o)) {
                return false;
    return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download