java 分组求和函数,Java分组依据:对多个字段求和

For the same problem, how do you return a list of Customer? For example, it should return:

Customer("A",4500,6500)

Customer("B",3000,3500)

Customer("C",4000,4500)

解决方案

@Pankaj Singhal's post is the right idea if you want a Map as the result set +1. However, I would extract the merging logic into its own function e.g. in the Customer class you would have a function as such:

public static Customer merge(Customer first, Customer second) {

first.setTotal(first.getTotal() + second.getTotal());

first.setBalance(first.getBalance() + second.getBalance());

return first;

}

Then the stream query would become:

Map retObj =

listCust.stream()

.collect(Collectors.toMap(Customer::getName, Function.identity(), Customer::merge));

listCust.stream() creates a stream object i.e. Stream.

collect performs a mutable reduction operation on the elements of

this stream using the provided Collector.

The result of toMap is the provided collector, the toMap method extracts the keys Customer::getName and values Function.identity() and if the mapped keys contain duplicates, the merge function Customer::merge is used to resolve collisions.

There are three benefits I see with extracting the merging logic into its own function:

The code is more compact.

The code is more readable.

The complexity of the merging is isolated away from the stream.

if however, your intention is to retrieve a Collection:

Collection result = listCust.stream()

.collect(Collectors.toMap(Customer::getName,

Function.identity(),

Customer::merge))

.values();

or List as the result set then all you have to do is call values() and pass the result of that to the ArrayList constructor:

List result = new ArrayList<>(listCust.stream()

.collect(Collectors.toMap(Customer::getName,

Function.identity(),

Customer::merge))

.values());

Update:

if you don't want to mutate the objects in the source then simply modify the merge function as follows:

public static Customer merge(Customer first, Customer second) {

Customer customer = new Customer(first.getName(), first.getTotal(), first.getBalance());

customer.setTotal(customer.getTotal() + second.getTotal());

customer.setBalance(customer.getBalance() + second.getBalance());

return customer;

}

and everthing else stays as is.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值