在 Java 8 中,如何对返回多个字段的单个字段进行分组。在下面的代码中,我传递名称和要求和的字段,在这种情况下为“总计”。但是我想返回客户列表中每个“名称”的“总计”和“余额”字段的总和(可以是键和值作为数组的映射)。
可以通过使用单个 groupingBy 和返回值来完成吗?
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class Sample {
public static void main(String str[]){
Customer custa = new Customer("A",1000,1500);
Customer custa1 = new Customer("A",2000,2500);
Customer custb = new Customer("B",3000,3500);
Customer custc = new Customer("C",4000,4500);
Customer custa2 = new Customer("A",1500,2500);
List<Customer> listCust = new ArrayList<>();
listCust.add(custa);
listCust.add(custa1);
listCust.add(custb);
listCust.add(custc);
listCust.add(custa2);
Map<String, Double> retObj =
listCust.stream().collect(Collectors.groupingBy(Customer::getName,Collectors.summingDouble(Customer::getTotal)));
System.out.println(retObj);
}
private static class Customer {
private String name;
private double total;
private double balance;
public Customer(String name, double total, double balance) {
super();
this.name = name;
this.total = total;
this.balance = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Customer [name=" + name + ", total=" + total + ", balance=" + balance + "]";
}
}
}
预期输出 -
{
A = [4500,6500],
B = [3000,3500] ,
C = [4000,4500]
}