Skip to content
章节导航

toSet

将流元素收集到 Set 集合中的收集器。

java
public static void main(String[] args) {
        // 1. 基本使用 - 自动去重
        Set<String> set = Stream.of("apple", "banana", "apple", "cherry")
                .collect(Collectors.toSet());
        System.out.println(set); // [banana, apple, cherry] 或 [apple, banana, cherry]
        // 注意:HashSet 不保证顺序

        // 2. 处理数字
        Set<Integer> numbers = Stream.of(1, 2, 2, 3, 3, 3, 4)
                .collect(Collectors.toSet());
        System.out.println(numbers); // [1, 2, 3, 4] - 自动去重

        // 3. 复杂操作链
        Set<String> longWords = Stream.of("java", "python", "javascript", "go", "rust")
                .filter(word -> word.length() > 3)
                .map(String::toUpperCase)
                .collect(Collectors.toSet());
        System.out.println(longWords); // [JAVA, JAVASCRIPT, PYTHON]
    }

默认实现是 HashSet,不保证顺序,可以使用特定 Set 实现

java
// 1. TreeSet(排序)
Set<String> treeSet = Stream.of("z", "a", "b", "c")
        .collect(Collectors.toCollection(TreeSet::new));
System.out.println(treeSet); // [a, b, c, z] - 自然排序

// 2. LinkedHashSet(保持插入顺序)
Set<String> linkedHashSet = Stream.of("z", "a", "b", "c")
        .collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(linkedHashSet); // [z, a, b, c] - 保持流中顺序