Java 8 stream: sum of units of same items

Viewed 1273

Is there a concise way to sum the units of the same type of items in a list with Java 8 streams? For example, suppose I have a list of three items:

{id: 10, units: 1}
{id: 20, units: 2}
{id: 10, units: 1}

I like a summary stream like:

{id: 10, units 2}
{id: 20, units 2}

which sums the units of items of the same id. Any ideas?


Here's Federico's solution (with Lombok):

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class So44348207 {

    public static void main(String[] args) {
        List<Item> items = Arrays.asList(
            new Item(10,1), new Item(20,2), new Item(10, 1)
        );

        Map<Long, Integer> results = items.stream().collect(
            Collectors.toMap(
                Item::getId,
                Item::getUnits,
                Integer::sum
                )
            );

        results.forEach( (k,v) -> System.out.println(
            String.format("{id: %d, units: %d}", k,v))
        );
    }

    @Data
    @AllArgsContructor
    public static class Item {
        Long id;
        Integer units;
    }
}

which correctly produces:

java So44348207 
{id: 20, units: 2}
{id: 10, units: 2}
2 Answers
Related