更好的方法进行流和?
我有一个对象
public class Sample {
private String Id;
...
private String acct;
private BigDecimal amt1;
private BigDecimal amt3;
}
,我想从列表
Id | acct | amt1 | amt2
1 | 1111 | 0.50 | 0.50
2 | 1112 | 0.50 | 0.50
中总结AMT1和AMT2的
Map<Object, Sample> map = collectedTxs.stream()
.collect(Collectors.toMap(
f -> f.getAcct(),
Function.identity(),
(s, a) -> new Sample(
s.getId(),
s.getAcct(),
s.getAmt1().add(a.getAmt1()),
s.getAmt2().add(a.getAmt2()),
), LinkedHashMap::new));
列表有什么更好的方法吗?我不想将结果重新分配到另一个示例对象。
I have an object
public class Sample {
private String Id;
...
private String acct;
private BigDecimal amt1;
private BigDecimal amt3;
}
I have a list
Id | acct | amt1 | amt2
1 | 1111 | 0.50 | 0.50
2 | 1112 | 0.50 | 0.50
I want to sum amt1 and amt2 from a list
Map<Object, Sample> map = collectedTxs.stream()
.collect(Collectors.toMap(
f -> f.getAcct(),
Function.identity(),
(s, a) -> new Sample(
s.getId(),
s.getAcct(),
s.getAmt1().add(a.getAmt1()),
s.getAmt2().add(a.getAmt2()),
), LinkedHashMap::new));
Is there any better way to do it? I don't want to reassign the result to another Sample object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
流旨在用于映射值。不建议在流环境外修改现有状态,因为它可能在某些情况下导致数据不一致。但是,您仍然可以使用Java 8+地图功能非常有效地做到这一点。 (流并不总是操纵数据的最佳或最有效的方法。使用循环没有错。)
这是我的做法。这是唯一更改的班级定义。
数据
流程
s
是每个帐户的第一个遇到的实例。双方函数
通过添加使用方法参考prints
将它们结合在一起,这是原始数据。请注意,迭代中遇到的第一个帐户已更改。
如果您想保留原始实例。然后在地图构造中进行以下更改。
Streams are meant to be used to map values. Modifying existing state outside of the stream environment is ill advised as it can cause data inconsistencies in certain situations. But you can still do it very efficiently using Java 8+ map features. (Streams is not always the best or most efficient way of manipulating data. There is nothing wrong with using loops.)
Here is how I would do it. Here is the class definition with the only changes being.
The Data
The Process
s
is the first encountered instance of each account.BiFunction
combines them via add using method referenceprints
Here is the original data. Note that the first accounts encountered in the iteration were changed.
If you want to preserve the original instances. Then make the following change in the map construct.