Using JDK 8 features to group data in a list

Use Case

Sorting has always been supported by Java. Recently, I came across a requirement in our project where we needed to group data in a list by some conditions, which can change based on the user selection. Traditionally, this would have been done by the sql statement’s GROUP BY clause in the DataAccess layer. But in our case, that would make the sql query very complex. So we decided to take the plunge and do the group by in the Service Layer using Java.

The Dao looks like this:

And the Service looks like this:

How to do it pre JDK 8

Pre JDK 8, Java does not provide group by out of the box. After ruling out hand-coding that logic, we decided to go with Google Guava’s ListMultimap. Its pretty cool actually. It stores in different values having the same key. Then, it exposes a List view of data with similar keys.

Note that we have to do it in 2 steps:

  1. Collect the data

  2. Iterate over the collected data and create a List view for each unique key

This sometimes becomes cumbersome, but is possibly one of the most elegant solutions pre JDK 8.

What changed in JDK 8?

Jdk 8 supports group by out of the box. No for loops, no 3rd party libraries. This is the code, short and sweet:

Again, note the absolute lack of for loops, which make the code crisp and more readable. Let me sum up how this is achieved:

  1. Create the Function for generating the key by which the data would be grouped. This Function would take a BankDetail object and supply a String. Note that the key can be any Object as long as it has a proper hashcode() method.

  2. Create a Collector using the Collectors.groupingBy() to collect the data

  3. From the un-grouped data, create a Stream, and apply the collector created above.

That simple!

The code can be found here:

2 thoughts on “Using JDK 8 features to group data in a list

  1. Hi,
    Very interesting post.
    But I probably missed something : the bankdetailDao tries to fetch the data from a mysql table, and I can’t find it, neither the way to setup the corresponding database.
    I am going to adapt your code to use my derby instance and create the expected database. but I was wondering if you perhaps missed to provide the data ?

    thank you !

Leave a Reply

Your email address will not be published. Required fields are marked *