![](/img/trans.png)
[英]Can I create a list using streams where the critera are to check one list then add an object to another list?
[英]Using streams how can I create a summary object
请假设我具有以下数据结构
public class Payment {
String paymentType;
double price;
double tax;
double total;
public Payment(String paymentType, double price, double tax, double total) {
super();
this.paymentType = paymentType;
this.price = price;
this.tax = tax;
this.total = total;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
在另一种方法中,我将具有如下类型的集合:
private Payment generateTotal() {
Collection<Payment> allPayments = new ArrayList<>();
allPayments.add(new Payment("Type1", 100.01, 1.12, 101.13));
allPayments.add(new Payment("Type2", 200.01, 2.12, 202.13));
allPayments.add(new Payment("Type3", 300.01, 3.12, 303.13));
allPayments.add(new Payment("Type4", 400.01, 4.12, 404.13));
allPayments.add(new Payment("Type5", 500.01, 5.12, 505.13));
//Generate the total with a stream and return
return null;
}
我想流这些映射到总对象
即
看起来像这样的付款对象
paymentType = "Total";
price = sum(payment.price);
tax = sum(payment.tax);
total = sum(payment.total);
我知道我可以一次使用mapToDouble一列来执行此操作,但是我想使用reduce或某种方法来使此操作在一个流中发生。
您可以将自己的Collector
实现为Payment
对象:
Payment total =
allPayments.stream()
.collect(Collector. of(
() -> new Payment("Total", 0.0, 0.0, 0.0),
(Payment p1, Payment p2) -> {
p1.setPrice(p1.getPrice() + p2.getPrice());
p1.setTax(p1.getTax() + p2.getTax());
p1.setTotal(p1.getTotal() + p2.getTotal());
},
(Payment p1, Payment p2) -> {
p1.setPrice(p1.getPrice() + p2.getPrice());
p1.setTax(p1.getTax() + p2.getTax());
p1.setTotal(p1.getTotal() + p2.getTotal());
return p1;
}));
没有理由在更短,更容易阅读类似内容的地方使用Streams:
Payment sum = new Payment("Total", 0, 0, 0);
allPayments.forEach(p -> {
sum.price += p.price;
sum.tax += p.tax;
sum.total += p.total;
});
正如评论中所讨论的,此解决方案不仅更短,更清洁(IMO),而且更易于维护:例如,说现在您有一个例外:您想继续对所有这些属性进行求和,但希望排除其中的项目第二个索引。 与简单的for循环相比,将其添加到reduce-verion有多容易?
有趣的是,该解决方案具有较小的内存占用空间(因为reduce每次迭代都会创建一个额外的对象),并且在提供的示例中可以更高效地运行。
缺点:我唯一能找到的是万一我们处理的集合很大(数千个或更多),在这种情况下,我们应该对Stream.parallel使用reduce解决方案,但即便如此,也应谨慎进行
通过以下方式在JMH中进行基准测试:
@Benchmark
public Payment loopIt() {
Collection<Payment> allPayments = new ArrayList<>();
allPayments.add(new Payment("Type1", 100.01, 1.12, 101.13));
allPayments.add(new Payment("Type2", 200.01, 2.12, 202.13));
allPayments.add(new Payment("Type3", 300.01, 3.12, 303.13));
allPayments.add(new Payment("Type4", 400.01, 4.12, 404.13));
allPayments.add(new Payment("Type5", 500.01, 5.12, 505.13));
Payment accum = new Payment("Total", 0, 0, 0);
allPayments.forEach(x -> {
accum.price += x.price;
accum.tax += x.tax;
accum.total += x.total;
});
return accum;
}
@Benchmark
public Payment reduceIt() {
Collection<Payment> allPayments = new ArrayList<>();
allPayments.add(new Payment("Type1", 100.01, 1.12, 101.13));
allPayments.add(new Payment("Type2", 200.01, 2.12, 202.13));
allPayments.add(new Payment("Type3", 300.01, 3.12, 303.13));
allPayments.add(new Payment("Type4", 400.01, 4.12, 404.13));
allPayments.add(new Payment("Type5", 500.01, 5.12, 505.13));
return
allPayments.stream()
.reduce(
new Payment("Total", 0, 0, 0),
(sum, each) -> new Payment(
sum.getPaymentType(),
sum.getPrice() + each.getPrice(),
sum.getTax() + each.getTax(),
sum.getTotal() + each.getTotal()));
}
结果:
Result "play.Play.loopIt":
49.838 ±(99.9%) 1.601 ns/op [Average]
(min, avg, max) = (43.581, 49.838, 117.699), stdev = 6.780
CI (99.9%): [48.236, 51.439] (assumes normal distribution)
# Run complete. Total time: 00:07:36
Benchmark Mode Cnt Score Error Units
Play.loopIt avgt 200 49.838 ± 1.601 ns/op
Result "play.Play.reduceIt":
129.960 ±(99.9%) 4.163 ns/op [Average]
(min, avg, max) = (109.616, 129.960, 212.410), stdev = 17.626
CI (99.9%): [125.797, 134.123] (assumes normal distribution)
# Run complete. Total time: 00:07:36
Benchmark Mode Cnt Score Error Units
Play.reduceIt avgt 200 129.960 ± 4.163 ns/op
我不会为此使用流,但是自从您问到:
Payment total =
allPayments.stream()
.reduce(
new Payment("Total", 0, 0, 0),
(sum, each) -> new Payment(
sum.getPaymentType(),
sum.getPrice() + each.getPrice(),
sum.getTax() + each.getTax(),
sum.getTotal() + each.getTotal()));
您需要一个BinaryOperator<Payment> accumulator
来组合两个Payment
:
public static Payment reduce(Payment p1, Payment p2) {
return new Payment("Total",
p1.getPrice() + p2.getPrice(),
p1.getTax() + p2.getTax(),
p1.getTotal() + p2.getTotal()
);
}
减少将如下所示:
Payment payment = allPayments.stream().reduce(new Payment(), Payment::reduce);
或(避免创建身份对象):
Optional<Payment> oPayment = allPayments.stream().reduce(Payment::reduce);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.