使用 Set 消除重复

假设你有一个集合 elements,并且你想要创建另一个包含相同元素的集合,但删除了所有重复项

Collection<Type> noDuplicates = new HashSet<Type>(elements);

示例

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

输出

noDuplicates = [Marco, Emily, John, Jenny]