Given n lists, I want to find out if any two lists have exactly same elements. Below is code in Java 7.
public static <T> boolean hasduplicateList(List<List<T>> lists) {
for (List<T> outerList : lists) {
int count = 0;
Set<T> outerSet = new HashSet<>(outerList);
for (List<T> innerList : lists) {
Set<T> innerSet = new HashSet<>(innerList);
if (outerSet.equals(innerSet)) {
count++;
}
if (count == 2) {
return true;
}
}
}
return false;
}
Is there a better way to achieve same specially using Java8?
Since in your Java 7 code you convert the List
s to Set
s before comparing them, it seems that you want to check whether at least 2 of the input List
s have the same set of elements (ignoring duplicates or order).
You can achieve this in Java 8 by streaming the List
and converting it to a Stream
of Set
s. Then all you have to do is find if the number of distinct Set
s is smaller than the size of the input List
:
public static <T> boolean hasduplicateList(List<List<T>> lists) {
return
lists.stream() // create a <Stream<List<T>>
.map(HashSet::new) // transform Stream<List<T>> to Stream<HashSet<T>>
.distinct() // keep only distinct Sets
.count() < lists.size();
}
Test :
public static void main (String[] args)
{
List<String> alist = Arrays.asList ("a","b","c");
List<String> blist = Arrays.asList ("b","c","c","a");
List<String> clist = Arrays.asList ("e","d","c","a");
List<List<String>> llist1 = Arrays.asList (alist,blist);
List<List<String>> llist2 = Arrays.asList (alist,clist);
System.out.println ("has dups? " + hasduplicateList (llist1));
System.out.println ("has dups? " + hasduplicateList (llist2));
}
Output :
has dups? true
has dups? false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With