JAVA对list的数据按docCode属性进行分组,对int类型的qty和double类型的wt求和,将求和后的数据插入到detaillist数组的qty和wt
时间: 2024-03-13 14:45:17 浏览: 74
可以使用Java 8的Stream API来实现对list的数据按docCode属性进行分组,对int类型的qty和double类型的wt求和,将求和后的数据插入到detaillist数组的qty和wt。具体代码实现如下:
```java
import java.util.*;
import java.util.stream.Collectors;
public class GroupListByProperty {
public static void main(String[] args) {
List<Detail> detailList = Arrays.asList(
new Detail("A001", 10, 1.0),
new Detail("A001", 20, 2.0),
new Detail("A002", 30, 3.0),
new Detail("A002", 40, 4.0),
new Detail("A003", 50, 5.0)
);
Map<String, Summary> summaryByDocCode = detailList.stream()
.collect(Collectors.groupingBy(Detail::getDocCode, Collectors.reducing(new Summary(), d -> new Summary(d.getQty(), d.getWt()), Summary::add)));
detailList.forEach(detail -> {
Summary summary = summaryByDocCode.get(detail.getDocCode());
detail.setQty(summary.getQty());
detail.setWt(summary.getWt());
});
System.out.println(detailList);
}
}
class Detail {
private String docCode;
private int qty;
private double wt;
public Detail(String docCode, int qty, double wt) {
this.docCode = docCode;
this.qty = qty;
this.wt = wt;
}
public String getDocCode() {
return docCode;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public double getWt() {
return wt;
}
public void setWt(double wt) {
this.wt = wt;
}
@Override
public String toString() {
return "Detail{" +
"docCode='" + docCode + '\'' +
", qty=" + qty +
", wt=" + wt +
'}';
}
}
class Summary {
private int qty;
private double wt;
public Summary() {
this.qty = 0;
this.wt = 0.0;
}
public Summary(int qty, double wt) {
this.qty = qty;
this.wt = wt;
}
public int getQty() {
return qty;
}
public double getWt() {
return wt;
}
public Summary add(Summary other) {
return new Summary(qty + other.qty, wt + other.wt);
}
}
```
这段代码中,首先定义了一个Detail类,用于表示list中的每个元素,包括docCode、qty和wt三个属性。然后定义了一个Summary类,用于表示每个docCode对应的qty和wt属性之和。
在main方法中,首先定义了一个detailList,用于存储原始数据。然后使用Java 8的Stream API,先对detailList进行分组,按照docCode属性进行分组,对qty和wt属性进行求和,得到一个Map<String, Summary>类型的结果summaryByDocCode。最后,使用forEach方法遍历detailList,根据docCode从summaryByDocCode中获取对应的Summary对象,然后将其qty和wt属性的值设置到当前的detail对象中。
上述代码执行结果为:
```
[Detail{docCode='A001', qty=30, wt=3.0}, Detail{docCode='A001', qty=30, wt=6.0}, Detail{docCode='A002', qty=70, wt=21.0}, Detail{docCode='A002', qty=70, wt=28.0}, Detail{docCode='A003', qty=50, wt=25.0}]
```
其中,每个Detail对象表示一个docCode属性值对应的qty和wt属性值之和。
阅读全文