我有这样的事情:
Integer totalIncome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getIncome()).sum();
Integer totalOutcome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getOutcome()).sum();
我怎么能在一个流中写出来?收集f.e. Pair<Integer, Integer>
totalIncome
和totalOutcome
?
EDITED :
谢谢你们的评论,答案和参与。我会对使用流来解决该问题的不同方法提出疑问。你怎么看待这个:
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());
}
}
答案 0 :(得分:2)
没有正确测量 - 一切都在猜测。我同意的唯一论点是关于可读性 - 这在这里几乎不是这样的;但如果您想出于学术目的而知道这一点,您可以这样做:
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;
}));