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

Say you are provided with a List<KVPair> , where each KVPair has String key , String Value and .equals() methods that do everything right.

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

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); 

One approach I can think of is to sort the list first and iterate to the next, like the previous one.

Is there an easier and clearer way to find the same?

+4
source share
3 answers

Here is a general solution:

Remember to do an empty check. The first time you add an item to a collection, 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; } 
+3
source

If hashCode () is also implemented correctly, you can add them all to the HashSet and see if you have duplicates:

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

or even (a little 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 
+3
source

Using java threads:

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

All Articles