java – struggling to understand List list = people.stream().map(Person::getName).collect(Collectors.toList());

java – struggling to understand List list = people.stream().map(Person::getName).collect(Collectors.toList());

  • The first method, people.stream() creates a Stream<Person>.
  • A transformation is specified by map(). Each Person in the stream will be converted to a String by invoking getName() on it. The Person::getName syntax is a method reference, and has a type of Function<Person,String> in this case. The result is a Stream<String>.
  • A Collector<String,?,List<String>> is created, using the factory method Collectors.toList().
  • The collect() method is a terminal operation; invoking it causes the Stream to be evaluated. The results are collected, producing a new List<String>.
List<String> list =
people.stream() // gets a Stream<Person> 
    .map(Person::getName) // for each Person object call the getName() method - producing a Stream<String> of the result of that method call
    .collect(Collectors.toList()); // collect that Stream<String> into a List, which is stored in the local variable declared as list

This can be written imperatively as

List<String> list = new ArrayList<>();
for (Person person : people) {
    list.add(person.getName());
}

java – struggling to understand List list = people.stream().map(Person::getName).collect(Collectors.toList());

Leave a Reply

Your email address will not be published. Required fields are marked *