Java thread. Summing two fields in an object stream

I have something like this:

Integer totalIncome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getIncome()).sum(); Integer totalOutcome = carDealer.getBrands().stream().mapToInt(brand -> brand.getManufacturer().getOutcome()).sum(); 

How could I write this in a single thread? to collect fe Pair<Integer, Integer> with totalIncome and totalOutcome ?

EDITED

Thank you guys for your comments, answers and participation. I would have a question about a different approach to this problem using threads. What do you think about it:

 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()); } } 
+5
source share
1 answer

Without the right measurement, everyone guesses. The only argument I agree with is readability - this is not the point; but if you want to know this for academic purposes, you can do this:

 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; })); 
+2
source

Source: https://habr.com/ru/post/1273445/


All Articles