Andrew
Andrew

Reputation: 451

Java sum a list of items based on properties

Given a class Item as below:

Class item {
 private Date date;
 private String id;
 private Double value;

 // getter and setter...
}

I would like to create a function that goes through a list of items and sum the value for the Items with the same date and id, and return the list of IDs and sum of value.

public Map<String, Double> process(List<Item> listItems, Date today) {
 // return list with ID and sum of the value for all the items group by ID and where the date equals the date in parameter.
}

So far I have looked at the Java 8 functions Stream and Collect and have been able to do this:

Map<String, Double> map = listTransactions.stream()
                .collect(Collectors.groupingBy(Item::getId, Collectors.summingDouble(Item::getValue)));

This is working fine to group by id but I'm not sure how to filter by date now so any help would be greatly appreciated.

Otherwise I could do it with a basic loop but I would like to find a better way to do it, using Java 8 if possible.

Upvotes: 0

Views: 1416

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may do it like so,

Map<String, Map<LocalDateTime, Double>> result = items.stream()
        .collect(Collectors.groupingBy(Item::getId,
                Collectors.groupingBy(Item::getDate, Collectors.summingDouble(Item::getValue))));

But the result type is not exactly the same what you need. In this case it is Map<String, Map<LocalDateTime, Double>>

Anyway here's my question to you, How are you going to handle same Id values with different date values in this case? How are you going to handle that conflict?

Upvotes: 1

Related Questions