使用流收集 return 相同的列表,切割和总结重复项,抛出一个非静态引用

Using stream collect to return the same list cutting and summing the duplicates, throwing a non-static reference

所以,我正在尝试 Return 一个列表的列表,但是对重复项进行剪切和求和,就像那样。

ID 1, VALUE 5
ID 1, VALUE 6
ID 2, VALUE 5
ID 3, VALUE 8
ID 3, VALUE 9

Return

ID 1, VALUE 11
ID 2, VALUE 5 
ID 3, VALUE 17

我在 Whosebug 中搜索并实现了这个,

list.stream().collect(
Collectors.groupingBy(ListDTO::getId, Collectors.summingDouble(ListDTO::getValue)));

所以,为了 return 一个列表,a 做到了,

list = list.stream().collect(
Collectors.groupingBy(ListDTO::getId, Collectors.summingDouble(ListDTO::getValue), Collectors.toList()));

但是,它现在给我这个错误

Non-static method cannot be referenced from a static context

具体在这里

ListDTO::getId

所以,谁能解释我的问题?或者对此有更好的方法?

我的列表DTO

@Getter
@Setter

public class ListDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    private Double value;

    private Long id;

    public ListDTO(){}

    public ListDTO(Double value, Long id){
        this.value = value;
        this.id = id;
    }
}

试试这个。您可以使用 toMap 具有合并功能的收集器。

 Map<Integer,ListDTO> mapById = list.stream()
     .collect(Collectors.toMap(ListDTO::getId,
                       Function.identity(),(l1,l2)->{l1.sumValue(l2);return l1;}));

然后

List<ListDTO> result = new ArrayList<>(mapById.values());

你应该声明一个方法

public ListDTO sumValue(ListDTO l){
     this.value += l.value;
     return this;
}