Group-by operation in Java Streams
We will see an example of Using group-by operation in Java Streams,
- Arithmetic operation on particular fields of a Class
- Sorting is needed on the basis of the field of a Class
- Perform metrics like mean, median on a particular field
- 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;
import java.util.stream.Collectors;
/**
* @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>();
carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
carList.add(car5);
carList.add(car6);
// Challenge is to group cars by Color
Map<String, List<Car>> groupByOnColor = carList.stream().collect(Collectors.groupingBy(Car::getColor));
System.out.println(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 = colourList.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
}
}
Output:
{red=[deekshithbennur.Car@3b9a45b3, deekshithbennur.Car@7699a589, deekshithbennur.Car@58372a00], White=[deekshithbennur.Car@4dd8dc3], white=[deekshithbennur.Car@6d03e736, deekshithbennur.Car@568db2f2]}
{orange=2, red=3, yellow=2}
Using group-by operation in Java Streams
To get more knowledge on Java click here.