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.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License