Java Stream How to - Filter Person List and map to name, then collect to create string








Question

We would like to know how to filter Person List and map to name, then collect to create string.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
//from   ww w .  ja  v a  2 s  .  co  m
public class Main {

  public static void main(String[] args) throws Exception {
    List<Person> persons =
        Arrays.asList(
            new Person("Max", 18),
            new Person("Peter", 23),
            new Person("Pamela", 23),
            new Person("David", 12));   
    

    String names = persons
        .stream()
        .filter(p -> p.age >= 18)
        .map(p -> p.name)
        .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));

    System.out.println(names);
  }

}
class Person {
  String name;
  int age;

  Person(String name, int age) {
      this.name = name;
      this.age = age;
  }

  @Override
  public String toString() {
      return name;
  }
}

The code above generates the following result.