所以,我试图返回一个列表的列表,但对重复项进行剪切和求和,就像这样。
ID 1, VALUE 5
ID 1, VALUE 6
ID 2, VALUE 5
ID 3, VALUE 8
ID 3, VALUE 9
返回
ID 1, VALUE 11
ID 2, VALUE 5
ID 3, VALUE 17
我在 StackOverflow 中搜索并实现了这个,
list.stream().collect(
Collectors.groupingBy(ListDTO::getId, Collectors.summingDouble(ListDTO::getValue)));
因此,为了返回一个列表,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;
}
关于java - 使用流收集返回相同的列表,对重复项进行切割和求和,抛出非静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807892/