2017-12-25 5 views
3

私は、次の2つのオブジェクトJava Streamsで余分な値を処理する方法は?

Product  ProductInventory 
-type   -Product 
-price  -quantity 
       -country 

を持っている私はProductInventoryのリストを反復処理で最も安いを見つける必要があります。ステップは次のとおりです。

  1. product.type == input_type場合と quantity > input_quantity
  2. totalPrice = product.price * input_quantity
  3. totalPrice = totalPrice + input_taxその後、 country != input_countryかの並べ替えレコード分から最大へ totalPrice
  4. ことにより、新しいオブジェクト(国、残りの量に最初のレコード&マップを取得、合計金額)

私は総価格を生成する必要があるステップ2をどのように処理するのかを考え出すことができませんが、&をストリーム内で使用する方法を教えてください。

+0

あなたは 'totalPrice'の値を持っています。これはどこにでも保存することはできません。なぜなら、その値を' ProductInventory'に追加しないのはなぜですか? –

+0

ラッパークラスを使用しましたか?またはインベントリクラスに直接挿入しますか? –

+1

productInventoryが別の目的を持っていることを知っているので、私はラッパークラスに挿入しようとしています。 – user1298426

答えて

2

totalPriceフィールドがProductInventoryに宣言されている場合は、次の操作を実行できます。

private Optional<FinalEntity> doLogic(String inputCountry, String inputType, Integer inputQuantity, Integer inputTax) { 
    return Stream.of(new Inventory(new Product("cola", 15), "germany", 1000)) 
      .filter(inv -> inv.getProduct().getType().equals(inputType) && inv.getQuantity() > inputQuantity) 
      .peek(inv -> { 
       Integer tax = inv.getCountry().equals(inputCountry) ? 0 : inputTax; 
       inv.setTotalPrice((inv.getProduct().getPrice() * inputQuantity) + tax); 
      }) 
      .sorted(Comparator.comparing(Inventory::getTotalPrice)) 
      .findFirst() 
      .map(Util::mapToFinalEntity); 
} 

どこ

public class Product { 

    String type; 
    Integer price; 

    // getters, setters, constructors 
} 

public class Inventory { 

    Product product; 
    String country; 
    Integer quantity; 
    Integer totalPrice; 

    // getters, setters, and constructors 
} 

結果値がいずれかのOptional.empty()である、またはあなたが最後のエンティティ形式で結果の値を持つことになります、私は、最後のmap to new object (country, quantity remaining, total price)をスキップその時点で簡単なステップ。

Inventoryにこのフィールドを入れたくない場合は、totalPriceを含むラッパークラスを作成し、ストリームの先頭にあるインベントリからマップすることができます。

+0

人工の 'peek'ではなく' map'を使わないのはなぜですか? – apophis

+0

@apophisマップを使用することは可能ですが、キーが重複している可能性があると考えた場合は、そのようなケースを考慮する必要があります。問題は、totalPrice値に対するラムダ解を持つ単一のストリームを持つことを求めていました。私の答えはまさにそれです。 –

+0

'ストリーム'のオブジェクトが変更されている場合、 'peek'を使用する@apophisは**必須**です。この場合、 'map'を使用すると、メソッドのコントラクトが破られ、結果がUBになります。 –

関連する問題