Skip to content

Instantly share code, notes, and snippets.

@gkhays
Last active October 10, 2019 17:40
Show Gist options
  • Save gkhays/e95ed57640f6b5a4970a827c86bb8a7b to your computer and use it in GitHub Desktop.
Save gkhays/e95ed57640f6b5a4970a827c86bb8a7b to your computer and use it in GitHub Desktop.
Compare members of different lists in Java

Java Collections has some built-in features; e.g. retainAll and removeAll.

//listOne.retainAll(listTwo);
listOne.removeAll(listTwo);

Note: Sets do not allow duplicates.

Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );

similar.retainAll( listTwo );
different.removeAll( similar );

System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);

Source: Java Compare Two Lists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment