DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Practical Generators in Go 1.23 for Database Pagination
  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  • What Is a Streaming Database?

Trending

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Emerging Data Architectures: The Future of Data Management
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Data Engineering
  3. Data
  4. Java Streams groupingBy Examples

Java Streams groupingBy Examples

Learn how to perform SQL-like grouping and summarizing calculations on Java Collections using CSV data, POJOs, and multiple fields.

By 
Jay Sridhar user avatar
Jay Sridhar
·
Mar. 24, 17 · Tutorial
Likes (38)
Comment
Save
Tweet
Share
136.0K Views

Join the DZone community and get the full member experience.

Join For Free

Have you wanted to perform SQL-like operations on data in a List or a Map? Maybe computing a sum or average? Or perhaps performing an aggregate operation such as summing a group? Well, with Java 8 streams operations, you are covered for some of these.

A previous article covered sums and averages on the whole data set. In this article, we show how to use Collectors.groupingBy() to perform SQL-like grouping on tabular data.

Define a POJO

Here is the POJO that we use in the examples below. It represents a baseball player.

public class Player {
    private int year;
    private String teamID;
    private String lgID;
    private String playerID;
    private int salary;


}


We load the following sample data representing player salaries.

yearID,teamID,lgID,playerID,salary
1985,ATL,NL,barkele01,870000
1985,ATL,NL,bedrost01,550000
...


Load CSV Data

Since the CSV is quite simple (no quoted fields, no commas inside fields, etc. See this article for code covering those cases), we use a simple regex-based CSV parser. The data is loaded into a list of POJOs.

Pattern pattern = Pattern.compile(",");
try (BufferedReader in = new BufferedReader(new FileReader(filename));){
    List<Player> players = in
        .lines()
        .skip(1)
        .map(line -> {
                String[] arr = pattern.split(line);
                return new Player(Integer.parseInt(arr[0]),
                                  arr[1],
                                  arr[2],
                                  arr[3],
                                  Integer.parseInt(arr[4]));
            })
        .collect(Collectors.toList());
}


Group by a Single Field

In an illustration of a simple usage of groupingBy(), we show how to group the data by year. The result is a map of year and players list grouped by the year.

    Map<Integer,List<Player>> grouped = in
        .lines()
        .skip(1)
        .map(line -> {
                String[] arr = pattern.split(line);
                return new Player(Integer.parseInt(arr[0]),
                                  arr[1],
                                  arr[2],
                                  arr[3],
                                  Integer.parseInt(arr[4]));
            })
        .collect(Collectors.groupingBy(x->x.getYear()));
    grouped
        .entrySet()
        .stream()
        .forEach(System.out::println);


1985=[{1985,ATL,NL,barkele01,870000}, {1985,ATL,NL ...
1986=[{1986,ATL,NL,ackerji01,367500}, {1986,ATL,NL ...


By Multiple Fields

Grouping by multiple fields is a little bit more involved because the resulting map is keyed by the list of fields selected. We create a List in the groupingBy() clause to serve as the key of the map. The value is the Player object.

The output map is printed using the for-each block below.

Map<List<String>,List<Player>> grouped = in
    .lines()
    .skip(1)
    .map(line -> {
            String[] arr = pattern.split(line);
            return new Player(Integer.parseInt(arr[0]),
                              arr[1],
                              arr[2],
                              arr[3],
                              Integer.parseInt(arr[4]));
        })
    .collect(Collectors.groupingBy(x -> {
                return new ArrayList<String>(Arrays.asList(Integer.toString(x.getYear()), x.getTeamID()));
            }));
grouped
    .entrySet()
    .stream()
    .forEach(x -> {
            System.out.println(x.getKey());
            x.getValue().stream()
                .forEach(p -> System.out.printf(" ( %2s %-10s %-10d )%n", p.getLgID(), p.getPlayerID(), p.getSalary()));
        });


[1987, PHI]
 ( NL aguaylu01 325000 )
 ( NL bedrost01 1050000 )
 ( NL calhoje01 85000 )
...


Eliminating the intermediate variable grouped, we have the entire processing pipeline in a single statement as shown below.

in
    .lines()
    .skip(1)
    .map(line -> {
            String[] arr = pattern.split(line);
            return new Player(Integer.parseInt(arr[0]),
                              arr[1],
                              arr[2],
                              arr[3],
                              Integer.parseInt(arr[4]));
        })
    .collect(Collectors.groupingBy(x -> {
                return new ArrayList<String>(Arrays.asList(Integer.toString(x.getYear()), x.getTeamID()));
            }))
    .entrySet()
    .stream()
    .forEach(x -> {
            System.out.println(x.getKey());
            x.getValue().stream()
                .forEach(p -> System.out.printf(" ( %2s %-10s %-10d )%n", p.getLgID(), p.getPlayerID(), p.getSalary()));
        });


Collecting Into a Set

The code above collects the results into the following type:

Map<List<String>,List<Player>>


Instead of storing the values in a List (inside the Map), how can we put it into a Set? We use the groupedBy() version that accepts the value-type.

Map<List<String>,Set<Player>> grouped = in
    .lines()
    .skip(1)
    .map(line -> {
            String[] arr = pattern.split(line);
            return new Player(Integer.parseInt(arr[0]),
                              arr[1],
                              arr[2],
                              arr[3],
                              Integer.parseInt(arr[4]));
        })
    .collect(Collectors.groupingBy(x -> return new ArrayList<String>(Arrays.asList(x.getTeamID(), x.getLgID())), Collectors.toSet()));


The first argument to groupingBy() is a lambda function which accepts a Player and returns a List of fields to group-by. The second argument is lambda which creates the Collection to place the results of the group-by.

This invocation collects the values into a Set which has no ordering. To retrieve values in the same order in which they were placed into the Set, use a LinkedHashSet as shown below (only the relevant portion is shown):

...
.collect(Collectors.groupingBy(x -> return new ArrayList<String>(Arrays.asList(x.getTeamID(), x.getLgID())), Collectors.toCollection(LinkedHashSet::new)));


Summarizing Field Values

Forget about collecting the results into a List or Set or whatever. What if we want to compute an aggregate of a field value? Say, for example, the sum of all salaries paid to players grouped by team and league.  Simple! Use a summingInt() as the second argument to groupingBy(). Remember the second argument collects the value-type of the group into the map.

Map<List<String>,Integer> grouped = in
    .lines()
    .skip(1)
    .map(line -> {
            String[] arr = pattern.split(line);
            return new Player(Integer.parseInt(arr[0]),
                              arr[1],
                              arr[2],
                              arr[3],
                              Integer.parseInt(arr[4]));
        })
    .collect(Collectors.groupingBy(x -> new ArrayList<String>(Arrays.asList(x.getTeamID(), x.getLgID())), Collectors.summingInt(Player::getSalary)));


Summary

Summarizing using grouping by is a useful technique in data analysis. Normally these are available in SQL databases. However using the Java 8 Streams and Collections facility, it is possible to use these techniques on Java collections. Some examples included grouping and summarizing with aggregate operations.

Java (programming language) Stream (computing) Database Data (computing)

Published at DZone with permission of Jay Sridhar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Practical Generators in Go 1.23 for Database Pagination
  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  • What Is a Streaming Database?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!