Reputation: 3763
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
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
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