Java Stream How to - Collect stream to List








Question

We would like to know how to collect stream to List.

Answer

/*ww w.  j  a  va  2 s  .  c o m*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class Main{
  public static void main(String[] argv){
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("Joe", 12));
    persons.add(new Person("Jim", 34));
    persons.add(new Person("John", 23));

    List<Person> list = persons.stream().filter(p -> p.getAge() > 18).collect(Collectors.toList());
    list.forEach(p -> System.out.println(p.getFirstName()));


  }
}
class MyWrapper {
  private Person person;

  public MyWrapper(Person person) {
      this.person = person;
  }

  public Person getPerson() {
      return person;
  }

  public void setPerson(Person person) {
      this.person = person;
  }
}
class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName) {
        this.firstName = firstName;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
      return "Person [firstName=" + firstName + ", lastName=" + lastName
          + ", age=" + age + "]";
    }
    
}

The code above generates the following result.