语法混乱:Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new))

Confusion over the syntax: Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new))

我正在尝试学习Java Set接口并且在网上遇到了以下代码,我理解这段代码的目的是将Collection<Object>转换为TreeSet,但我不明白该语句是如何工作的,因为语法对我来说很复杂而且很陌生。有人可以逐步指导我完成整个过程吗?

Set<String> set = people.stream()
                        .map(Person::getName)
                        .collect(Collectors.toCollection(TreeSet::new));

还有,在什么情况下我们应该更喜欢上面的语法而不是下面的语法?

Set<Integer> s1 = new TreeSet(c1); //where c1 is an instance of Collection interface type

peopele.stream() 创建元素流 .map(Person::getName) 从 people 集合中获取每个对象并调用 getName ,然后转换为字符串 .collect(Collectors.toCollection(TreeSet::new)) - 收集这些 String 元素并从中创建一个 TreeSet。

希望一切顺利

people.stream()

取一组人,得到一个流

.map(Person::getName)

获取人流并对每个人调用 getName 方法,返回包含所有结果的列表。这将是 "equivalent" 到

for(Person person : people){
    setOfNames.add(person.getName())
}

.collect(Collectors.toCollection(TreeSet::new));

获取字符串流并将其转换为一个集合。


当您需要应用多个转换时,流非常有用。如果您使用并行流,它们也可以执行得很好,因为每个转换(在您的情况下每个 getName)都可以并行而不是顺序完成。