Java 8 Streams groupingBy examples

In this tutorial we will provide some examples of how to use Java 8 streams groupingBy functionality.

Java 8 streams groupingBy and count

This first example will show how you can group elements in a List and then count the number of times they appeared in the list.

Executing the above code produces the following output

Java 8 streams groupingBy on a List of objects

The following example uses grouping on a list of objects.

Running the above code produces the following:

From the above output you can see that customers have been grouped based on their TV package. You can modify the returned map by using the mapping() method. The example below shows you can group customer names based on TV package (instead of the whole customer object).

This produces:

As you can see with this example the second parameter to collect() allows you to modify the returned map. In the above example we have grouped customer names based on their TV package.

Java 8 streams groupingBy with summing

The final example shows how to use the summing operation in a groupingBy context. Collectors have a summingDouble() (also for Int and Longs) method which will produce a sum based on your grouping. Collectors also have another useful method called summarizingDouble (also for Int and Longs) which will provide count, sum, min, max and average based on your grouping.

Running the above code produces the following

In conclusion I hope you found this post useful and it has given you a better understanding of how to use groupingBy with java streams.

Similar posts:

  1. Java 8 Stream map examples
  2. Java 9 Collections factory method
  3. Java 8 Comparator examples
  4. How to convert JSON string to a Java object


  1. Java 8 Collectors API documentation

Leave a Reply

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