1

I'm learning about lambda expressions. From a list of people, I want another list with the people who are older than 20 years.

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);

I have the impression that only the first two parameters are sufficient ArrayList::new and ArrayList::add.

How and when is used the third parameter ArrayList::addAll on my exemple?

Jesus Zavarce
  • 1,729
  • 1
  • 17
  • 27
  • https://stackoverflow.com/questions/29959795/how-does-combiner-in-stream-collect-method-work-in-java-8 – Eran Nov 26 '18 at 08:32
  • 1
    @GhostCat I tried to delete my question because it is duplicate. Your solution is ok for me. I know that is the better way to create another list, I just did this exemple for learning propose. – Jesus Zavarce Nov 26 '18 at 09:35
  • 1
    See https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled ... there is no *need* to delete duplicated questions. And honestly. And even answers on closed-as-dup sometimes help future readers ;-) ... and given the fact how many low quality Q/Ss show up here all day long, why bother about the good content here ;-) x2 – GhostCat Nov 26 '18 at 09:51
  • @Eran https://stackoverflow.com/questions/31533316/about-collect-supplier-accumulator-combiner :) – Jesus Zavarce Nov 26 '18 at 14:39

1 Answers1

1

The "correct" answer for this problem: to use collect(Collectors.toList()). There is simply no sense in using the 3 arg version of collect() unless you have to. See here for more details.

For how to use that 3 arg collect(), start reading here.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • The closest you can get to needing an additional parameter for this is probably something like `collect(toCollection(CopyOnWriteArrayList::new))`. – daniu Nov 26 '18 at 08:43