I have a List of objects List<FloatBalance>
which can be represented by the following JSON. I want to get the most recent entry for each currency in the List and pass the pruned list back to the request.
{
"id": 1,
"clientId": 50,
"currency": "GBP",
"floatType": "ChargeFloat",
"floatCurrentValue": 300.00,
"chargeReference": "PROD-1578486576_278",
"cashOutReference": null,
"cashInReference": null,
"targetValue": 3000.00,
"alertValue": 500.00,
"maxValue": 4500.00,
"createdDate": "2020-01-08T12:29:50Z"
},
...
]
My first attempt is straight foward, I group them by currency with
Map<String, List<FloatBalance>> result = floats.stream()
.collect(groupingBy(FloatBalance::getCurrency));
and then I group them and order them by most recent date with
Map<String, List<FloatBalance>> floatGrouped = floats.stream()
.sorted(Comparator.comparing(FloatBalance::getCreatedDate).reversed())
.collect(groupingBy(FloatBalance::getCurrency));
Map Result
I can also reduce the list but I have only been able to carry out this operation on the complete list which returns only the most recent entry.
FloatBalance floatGrouped = floats.stream()
.sorted(Comparator.comparing(FloatBalance::getCreatedDate))
.reduce((first, second) -> second)
.orElse(null);
I have gone round in circles trying to figure this out, I've tried to .entrySet()
to carry out reduce on each entry in the map but computer says no to everything I've tried.
Ideally I want to retrun the most recent entry for each currency as the system response.