adam bien's blog

Java 8 partitioningBy Example 📎

A developer has a favorite programming language:


public class Developer {

    private int age;
    private String favoriteLanguage;

    public Developer(int age, String favoriteLanguage) {
        this.age = age;
        this.favoriteLanguage = favoriteLanguage;
    }

    public int getAge() {
        return age;
    }

    public String getFavoriteLanguage() {
        return favoriteLanguage;
    }

    @Override
    public String toString() {
        return "Developer{" + "age=" + age + ", favoriteLanguage=" + favoriteLanguage + '}';
    }
}

A team has more than one developers. Now we would like to know which programming languages are used by developers younger than 30. Collectors#partitioningBy expects a Predicate (filter) which "partitions" all developers into two buckets identified by a "boolean":

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Test;

public class PartitioningByTest {

    @Test
    public void partitionByAge() {

        List<Developer> team = Arrays.asList(
                new Developer(18, "java"),
                new Developer(20, "java"),
                new Developer(35, "javascript"),
                new Developer(50, "javascript"),
                new Developer(50, "logo"));

        Map<Boolean, List<Developer>> youngerThan30 = team.
                stream().
                collect(Collectors.partitioningBy(d -> d.getAge() < 30));
        System.out.println("Developers younger than thirty are using: " + youngerThan30.get(true).stream().
		map(d -> d.getFavoriteLanguage()).
		collect(Collectors.toSet()));
        //Output: Developers younger than thirty are using: [java]
        System.out.println("Developers older than thirty are using: " + youngerThan30.get(false).stream().
		map(d -> d.getFavoriteLanguage()).
		collect(Collectors.toSet()));
        //Output: Developers older than thirty are using: [logo, javascript]
    }
}

Related: Java 8 CompletableFuture Example

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.