使用 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]