我有以下对象列表,我想按3个属性对它们进行分组并将第4个属性相加
public class DTO {
private final String at1;
private final String at2;
private final Integer at3;
private final BigDecimal amount;
}
我做了类似以下的操作,但是它导致了很多地图,而且由于需要一些逻辑,所以我无法求和
List<DTO> list = ...
Map<String, Map<String, Map<Integer, List<DTO>>>> groupedItems =
list.stream()
.collect(
Collectors.groupingBy(e -> e.getAt1(),
Collectors.groupingBy(e -> e.getAt2(),
Collectors.groupingBy( e -> e.getAt3()))));
如何获取具有求和逻辑的分组列表的列表?
您可以创建一个构造函数,其中包含要与之分组的三个属性:
public DTO(String at1, String at2, Integer at3) {
this.at1 = at1;
this.at2 = at2;
this.at3 = at3;
}
然后您可以使用:
Map<DTO, BigDecimal> groupedItems = list.stream()
.collect(Collectors.groupingBy(e -> new DTO(e.getAt1(), e.getAt2(), e.getAt3()),
Collectors.reducing(
BigDecimal.ZERO,
DTO::getAmount,
BigDecimal::add)));
我认为您是最重要的,equals
并且hashCode
在DTO课程中。
例:
List<DTO> list = new ArrayList<>();
list.add(new DTO("a", "b", 1, BigDecimal.valueOf(10)));
list.add(new DTO("z", "y", 4, BigDecimal.valueOf(20)));
list.add(new DTO("a", "b", 1, BigDecimal.valueOf(30)));
list.add(new DTO("a", "b", 1, BigDecimal.valueOf(40)));
产出
DTO{at1='a', at2='b', at3=1, amount=null} - 80
DTO{at1='z', at2='y', at3=4, amount=null} - 20
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句