gpt4 book ai didi

java-8 - Java 8 groupingby 返回多个字段

转载 作者:行者123 更新时间:2023-12-04 13:56:48 32 4
gpt4 key购买 nike

在 Java 8 group by 如何对返回多个字段的单个字段进行分组。在下面的代码中,我传递了名称和要求和的字段,在这种情况下为“总计”。但是我想为客户列表中的每个“名称”返回“总计”和“余额”字段的总和(可以是一个键和值作为数组的映射)。
可以通过使用带有返回值的单个 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]
}

最佳答案

您可以编写自己的收集器来汇总和平衡

Collector<Customer, List<Double>, List<Double>> collector = Collector.of(
() -> Arrays.asList(0.0, 0.0),
(a, t) -> {
a.set(0, a.get(0) + t.getTotal());
a.set(1, a.get(1) + t.getBalance());
},
(a, b) -> {
a.set(0, a.get(0) + b.get(0));
a.set(1, a.get(1) + b.get(1));
return a;
}
);

Map<String, List<Double>> retObj = listCust
.stream()
.collect(Collectors.groupingBy(Customer::getName, collector));

System.out.println(retObj);

结果
{A=[4500.0, 6500.0], B=[3000.0, 3500.0], C=[4000.0, 4500.0]}

关于java-8 - Java 8 groupingby 返回多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48728341/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com