Java 8 - Stream filter(), forEach(), collect() and Collectors.toList() Example



In this source code example, we will learn how to use Stream methods filter(), forEach(),collect() and Collectors.toList() with an example.

Java 8 - Stream filter(), forEach(), collect() and Collectors.toList() Example

The following example demonstrates how to use filter a List of persons based on Gender using Stream filter(), forEach(), collect() and Collectors.toList() methods:
package com.java.tutorials.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JavaStreamExample {

    public static void main(String[] args) {
        List < Person > people = getPeople();

        // Imperative approach

        List < Person > females = new ArrayList < > ();
        for (Person person: people) {
            if (person.getGender().equals(Gender.FEMALE)) {
                females.add(person);
            }
        }
        females.forEach(System.out::println);

        System.out.println(" **************** ");
        // Declarative approach 

        // Filter
        List < Person > females1 = people.stream().filter(person - > person.getGender().equals(Gender.FEMALE))
            .collect(Collectors.toList());

        females1.forEach(System.out::println);
    }

    private static List < Person > getPeople() {
        return List.of(new Person("Antonio", 20, Gender.MALE), new Person("Alina Smith", 33, Gender.FEMALE),
            new Person("Helen White", 57, Gender.FEMALE), new Person("Alex Boz", 14, Gender.MALE),
            new Person("Jamie Goa", 99, Gender.MALE), new Person("Anna Cook", 7, Gender.FEMALE),
            new Person("Zelda Brown", 120, Gender.FEMALE));
    }
}

enum Gender {
    MALE,
    FEMALE
}

class Person {

    private final String name;
    private final int age;
    private final Gender gender;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Gender getGender() {
        return gender;
    }

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender=" + gender + '}';
    }
}
Output:
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Anna Cook', age=7, gender=FEMALE}
Person{name='Zelda Brown', age=120, gender=FEMALE}
 **************** 
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Anna Cook', age=7, gender=FEMALE}
Person{name='Zelda Brown', age=120, gender=FEMALE}

Comments