我正在尝试学习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
> people.stream()
带走一群人,获得一条溪流。
.map(Person::getName)
获取人员流,并对每个人调用 getName
方法,返回包含所有结果的列表。这将"等同于"于
for(Person person : people){
setOfNames.add(person.getName())
}
.collect(Collectors.toCollection(TreeSet::new));
获取字符串流并将其转换为集合。
当您需要应用多个转换时,流非常有用。如果您使用并行流,它们也可以表现得很好,因为每个转换(在您的情况下每个getName
)都可以并行完成,而不是顺序完成。
peopele.stream() 创建一个元素流.map(Person::getName) 从 people 集合中获取每个对象并调用 getName,然后.collect(Collectors.toCollection(TreeSet::new)) - 收集这些字符串元素并从中创建 TreeSet。
希望它清楚