使用lambda表达式来总结成员变量?

Sup*_*hne 5 java lambda multithreading java-8 java-stream

我有一个类似于以下的课程.

public class Votes{
    String name;
    int likes;
    int dislikes;

    //constructors, getters and setters    
}
Run Code Online (Sandbox Code Playgroud)

我有一个如下列表.

List<Votes> votesList;
Run Code Online (Sandbox Code Playgroud)

假设我在列表中填充了一些元素.我想声明一个在该列表中执行分组和求和操作的方法.

作为一个例子,假设我在列表中给出了以下元素作为该input方法.

votesList.add(new Votes("A", 10, 5));
votesList.add(new Votes("B", 15, 10));
votesList.add(new Votes("A", 20, 15));
votesList.add(new Votes("B", 10, 25));
votesList.add(new Votes("C", 10, 20));
votesList.add(new Votes("C", 0, 15));
Run Code Online (Sandbox Code Playgroud)

该方法应输出List<Votes>具有以下元素的a.

("A", 30, 20),
("B", 25, 35),
("C", 10, 35)
Run Code Online (Sandbox Code Playgroud)

在Java8中使用stream,lambda表达式有一种简单的方法吗?我知道collectors如果我只有一个intmemeber 可以使用它.

有人可以解释一下我该如何解决这种情况?

Sup*_*hne 3

最后,我发现这是最简单的方法。:))

Map<String, List<Votes>> grouped = voteCountList.stream().collect(Collectors.groupingBy(r->r.getName()));

List<Votes> collectedList = new ArrayList<>();

grouped.forEach((groupName, votes) -> collectedList.add(new Votes(groupName,
                votes.stream().collect(Collectors.summingInt(r->r.getLikes())),
                votes.stream().collect(Collectors.summingInt(r->r.getDislikes())))));
Run Code Online (Sandbox Code Playgroud)