我有一张这样的 map (按键是客户编号 1、2、3、4 等。
Map<Long,List<Customer>> customerMap = new HashMap<Long, List<Customer>>();
public class Customer {
private String name;
private BigDecimal salary;
//..getter and setters
我想通过分组名称字段将其转换为另一个 map 。我想创建这样的 map
Map<Long,Map<String,CustomerSalary>> convertedMap = new HashMap<Long,Map<String,CustomerSalary>>()();
public class CustomerSalary {
private BigDecimal salary;
private BigDecimal remainingSalary;
//getter and setters.
我所做的是
`Map<Long,Map<String,CustomerSalary>> convertedMap =customerMap.entrySet()..stream()
.collect(Collectors.toMap( //collect the entries into another map
entry -> entry.getKey(),
entry -> entry.getValue().stream()
.collect(groupingBy(Customer::getName,
reducing(BigDecimal.ZERO, Customer::getSalary, BigDecimal::add)))
));
但不起作用,因为 CustomerSalary 应该是,但减少会创建 BigDecimal。你有什么想法吗?
不是:Salary 和剩余Salary 最初应该相同。
最佳答案
如果您想对salary
求和,可以使用reducing()
收集器:
entry.getValue().stream()
.collect(groupingBy(Customer::getName,
reducing(BigDecimal.ZERO, Customer::getSalary, BigDecimal::add)))
如果您希望结果为 CustomerSalary
,您可以向您的类或 sum 添加类似的运算符,并通过 collectingAndThen()
包装。
关于java - 通过对某些字段进行分组,将 java hashMap 转换为另一个 hashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71121950/