Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for duplicate lists Java 8

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?

like image 384
bpsingh Avatar asked Mar 10 '23 11:03

bpsingh


1 Answers

Since in your Java 7 code you convert the Lists to Sets before comparing them, it seems that you want to check whether at least 2 of the input Lists 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 Sets. Then all you have to do is find if the number of distinct Sets 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
like image 183
Eran Avatar answered Mar 30 '23 07:03

Eran