ecstasy :
I have a class -
public class LocationStats {
private String state;
private String country;
private int latestTotalCases;
private int diffFromPrevDay;
private int diffFromPrev2Day;
private int diffFromPrev3Day;
}
Top Sum-up total cases for a country I used below snippet, which is working fine.
List<LocationStats> newStats= getData();
Map<String, Integer> collect =
newStats
.stream()
.collect(Collectors.groupingBy(LocationStats::getCountry, Collectors.summingInt(LocationStats::getLatestTotalCases)));
I want to sum-up the other 3 attribues as well while processing the above-mentioned snippet. Is it possible ? Is there any Lambda-elegant way to achieve that ?
Eran :
You can use Collectors.toMap
with a merge function.
For example:
Map<String,LocationStats> sums =
newStats.stream()
.collect(Collectors.toMap(LocationStats::getCountry,
Function.identity(),
(s1,s2)->new LocationStats(s1,s2)));
You'll have to create a LocationStats
constructor that accepts two LocationStats
instances and creates an instance that contains the sums of the properties of those two instances:
public LocationStats (LocationStats s1, LocationStats s2)
{
this.state = s1.state;
this.country = s1.country;
this.latestTotalCases = s1.latestTotalCases + s2.latestTotalCases;
this.diffFromPrevDay = s1.diffFromPrevDay + s2.diffFromPrevDay;
this.diffFromPrev2Day = s1.diffFromPrev2Day + s2.diffFromPrev2Day;
this.diffFromPrev3Day = s1.diffFromPrev3Day + s2.diffFromPrev3Day;
}