Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform group by, count and sum from list of object in single stream and store in another list of object?

I am trying to get the group by, count and sum from list of the object using java stream and collection. I am not sure how do I achieve the desired result.

InputModel

String month;
BigDecimal salary;
String department;
String noOfEmp;

InputModel[(May,100,IT,10), (June,300,IT,7),(July,300,IT,7),(May,1000,HR,5), (June,300,HR,7),(July,600,HR,5)]

OutputModel

String month
BigDecimal salary
String noOfEmp

Expected Output OutputModel[(May,1100,15),(June,600,14),(July,900,12)]

I tried below code but it returned group by and Count.

Map<String, Integer> result= inputModels.parallelStream().collect(Collectors.groupingBy(InputModel::getMonth,
            LinkedHashMap::new, Collectors.summingInt(InputModel::getNoOfEmp)));

Thanks in Advance!!!

like image 230
user1127643 Avatar asked Mar 04 '23 02:03

user1127643


1 Answers

Given that you have OutputModel class in place, this will solve your problem.

Collection<OutputModel> outputModels = inputModel.stream()
    .map(im -> new OutputModel(im.getMonth(), im.getSalary(), im.getNoOfEmp()))
    .collect(Collectors.toMap(OutputModel::getMonth, Function.identity(),
        (m1, m2) -> new OutputModel(m1.getMonth(), m1.getSalary().add(m2.getSalary()),
            String.valueOf(Integer.valueOf(m1.getNoOfEmp()) + Integer.valueOf(m2.getNoOfEmp()))),
        LinkedHashMap::new))
    .values();

Word of caution: Better NOT to use Strings where other types are more appropriate. For an instance you should have used int to represent noOfEmp instead of a String. That would simplify the code while reducing the possibility of runtime errors due to spurious data. Moreover consider using java.time.Month enum to represent month of the year contrary to using String literals.

Here's the output,

[{month=May, salary=1100, noOfEmp=15}, {month=June, salary=600, noOfEmp=14}, {month=July, salary=900, noOfEmp=12}]

like image 104
Ravindra Ranwala Avatar answered Apr 07 '23 15:04

Ravindra Ranwala