Suppose you have a collection elements
, and you want to create another collection containing the same elements but with all duplicates eliminated:
Collection<Type> noDuplicates = new HashSet<Type>(elements);
Example:
List<String> names = new ArrayList<>(
Arrays.asList("John", "Marco", "Jenny", "Emily", "Jenny", "Emily", "John"));
Set<String> noDuplicates = new HashSet<>(names);
System.out.println("noDuplicates = " + noDuplicates);
Output:
noDuplicates = [Marco, Emily, John, Jenny]