Group-by operation in Java Streams

We will see an example of Using group-by operation in Java Streams, 

  1. Arithmetic operation on particular fields of a Class
  2. Sorting is needed on the basis of the field of a Class
  3. Perform metrics like mean, median on a particular field
  4. Count the number of occurrence of an entry in the list

It is good sometimes to memorize a few of the operations, as you might or might not get a chance to use IDE at the time of the interview.

Java streams provide an added advantage is it reduces the number of lines of code and also increases the readability of the code as well.

In terms of complexity and performance, it remains mostly the same as it is only the change in syntax and not the underlying logic.

Example Code :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

* @author deekshithbg
public class Test1 {

* @param args
public static void main(String[] args) {
Car car1 = new Car(“Maruthi”, “red”, 1991);
Car car2 = new Car(“Hyndai”, “White”, 2003);
Car car3 = new Car(“Maruthi”, “white”, 2003);
Car car4 = new Car(“Mahindra”, “red”, 1991);
Car car5 = new Car(“Mahindra”, “white”, 2003);
Car car6 = new Car(“Hyndai”, “red”, 1991);

List<Car> carList = new ArrayList<Car>();

// Challenge is to group cars by Color

Map<String, List<Car>> groupByOnColor =;

List<String> colourList = Arrays.asList(“red”, “red”, “yellow”, “red”, “orange”, “yellow”, “orange”);

// Challenge is to find out the occurence of an entry in the list

Map<String, Long> result =
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));





{red=[[email protected], [email protected], [email protected]], White=[[email protected]], white=[[email protected], [email protected]]}
{orange=2, red=3, yellow=2}

Using group-by operation in Java Streams

To get more knowledge on Java click here.

And also if you required any technology you want to learn, let us know below we will publish them in our site

Like our page in Facebook and follow us for New technical information.

Leave a Reply

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