use*_*850 6 java java-8 java-stream
我有这样的事情:
Integer totalIncome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getIncome()).sum();
Integer totalOutcome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getOutcome()).sum();
Run Code Online (Sandbox Code Playgroud)
我怎么能在一个流中写出来?Pair<Integer, Integer>用totalIncome和收集fe totalOutcome?
编辑:
谢谢你们的评论,答案和参与.我会对使用流来解决该问题的不同方法提出疑问.你怎么看待这个:
final IncomeAndOutcome incomeAndOutcome = carDealer.getBrands()
.stream()
.map(Brand::getManufacturer)
.map(IncomeAndOutcome::of)
.reduce(IncomeAndOutcome.ZERO, IncomeAndOutcome::sum);
static class IncomeAndOutcome {
private static final IncomeAndOutcome ZERO = of(0, 0);
@Getter
private final int income;
@Getter
private final int outcome;
public static IncomeAndOutcome of(final int income, final int outcome) {
return new IncomeAndOutcome(income, outcome);
}
public static IncomeAndOutcome of(final Manufacturer manufacturer) {
return new IncomeAndOutcome(manufacturer.getIncome(), manufacturer.getOutcome());
}
IncomeAndOutcome(final int income, final int outcome) {
this.income = income;
this.outcome = outcome;
}
IncomeAndOutcome sum(final IncomeAndOutcome incomeAndOutcome) {
return of(this.income + incomeAndOutcome.getIncome(), this.outcome + incomeAndOutcome.getOutcome());
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有正确测量——一切都是猜测。我唯一同意的论点是关于可读性——这里的情况几乎不是这样;但如果您出于学术目的想了解这一点,您可以这样做:
int[] result = carDealer.getBrands()
.stream()
.map(brand -> new int[]{brand.getManufacturer().getIncome(),
brand.getManufacturer().getOutcome()})
.collect(Collector.of(
() -> new int[2],
(left, right) -> {
left[0] += right[0];
left[1] += right[1];
},
(left, right) -> {
left[0] += right[0];
left[1] += right[1];
return left;
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |