【问题标题】:How is used the third parameter (combiner) of collect method? [duplicate]collect方法的第三个参数(combiner)怎么用? [复制]
【发布时间】:2018-11-26 08:27:39
【问题描述】:

我正在学习 lambda 表达式。 从人员列表中,我想要另一个包含 20 岁以上人员的列表。

final List<Person> people = Arrays.asList(
        new Person("John", 10),
        new Person("Greg", 30),
        new Person("Sara", 20),
        new Person("Jane", 15));

 List<Person> olderThan20 =
        people.stream()
       .filter(person -> person.getAge() > 20)
                    .collect(ArrayList::new, 
                             ArrayList::add, 
                             ArrayList::addAll);

我的印象是只有前两个参数就足够了ArrayList::newArrayList::add

在我的示例中,第三个参数ArrayList::addAll 是如何以及何时使用的?

【问题讨论】:

标签: java lambda


【解决方案1】:

这个问题的“正确”答案:使用collect(Collectors.toList())。除非您必须这样做,否则使用 collect() 的 3 arg 版本根本没有任何意义。有关详细信息,请参阅here

关于如何使用这 3 个参数 collect(),开始阅读 here

【讨论】:

  • 最接近需要额外参数的可能是collect(toCollection(CopyOnWriteArrayList::new))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多