1

I have an ArrayList (inputList) that parse this data:

id,name,quantity
1,foo,10
2,bar,20
3,foo,10
4,bar,10
5,qwerty,1

Code:

...
List<FooRow> inputList = new ArrayList<FooRow>();
inputList = br.lines().map(mapToFooRow).collect(Collectors.toList());
...

public class FooRow{
private Integer id;
private String name;
private Integer value;
}

I want to create a collectors that return me a list with the count of value grouped by name:

name,value
foo,20
bar,30
qwerty,1

How can I create a class Collectors to do this in the lambda expression? Thanks.

0

1 Answer 1

2

You can use Collectors.groupingBy and Collectors.summingInt:

Map<String, Integer> result =
    inputList.stream()
             .collect(Collectors.groupingBy(
                 FooRow::getName, Collectors.summingInt(FooRow::getValue)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.