2017-11-16 1 views
5

の流れの中で二つのフィールドを合計:Javaストリーム。私はこのような何かを持っているオブジェクト

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

は、どのように私はその内の1つのストリームを書くことができますか? f.e.を収集する。 Pair<Integer, Integer>totalIncometotalOutcome

EDITED

は、あなたのコメントみんな、回答、およびinvolvmentありがとうございます。私は、ストリームを使ってその問題への異なるアプローチについて質問します。あなたはそれについてどう思いますか:

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

ます(totalIncome、totalOutcome)>新しいペアを<返す 'もしかして;'? –

+0

はい、私はストリームを2回呼び出すことは効率的ではないと思います(最初は '収入'、2回目は '結果 ')。そして、私は彼らに参加して最終的に「収入」と「成果」の合計を返すただ一つの流れを得ることができるのだろうかと思っていましたか? – user3529850

+0

ループを使い、2つのフィールドに基づいて2つの合計をインクリメントしたい場合は、繰り返します。 – Pshemo

答えて

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

減量はステートレスでなければなりません。おそらく 'collect()'を代わりに使用し、同じ 'accumulator'と' combiner'を使うべきです。 – shmosel

+0

@shmosel right ...あまりにも多くのコーディング。 thx – Eugene

+0

特徴やフィニッシャーを渡さない限り、 'Collector'は必要ありません。 ['collect(supplier、accumulator、combiner)'](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.function)を呼び出してください。 .Supplier-java.util.function.BiConsumer-java.util.function.BiConsumer-)。 – shmosel

関連する問題