更新は、ストリームを使用して、二番目の値に基づいてつのリスト内のオブジェクト

私のやり方 :

私は2つの対応するリストを持っています:

public class BookOverallData {
    private Long idOfBook;
    private String title;
    private String authour;
    private BigDecimal basePrice;
    private Integer discountRate;
}

public class TimeDiscount {    
    private Long idOfBook;
    private Integer discountRate;    
}

Set<BookOverallData> booksToReturn
Set<TimeDiscount> actualPromotions

目標は、手段が追加割引、合計することであるdiscountRateからactualPromotionsdiscountRateから値booksToReturnリストを。両方のリストからオブジェクトがで一致させることができますidOfBook

これは私がそれを解決する方法であります

booksToReturn.forEach(
            p -> {
                final Optional<TimeDiscount> promotion = actualPromotions.stream().filter(ap -> Objects.equals(ap.getIdOfBook(), p.getIdOfBook())).findFirst();
                promotion.ifPresent(ap -> p.setDiscountRate(ap.getDiscountRate() + p.getDiscountRate()));
            }
        );

私はちょうどストリームを模索していると私は私の解決策は、塊状のだと思います。どのようにストリームと機能的アプローチの使用で、よりエレガントな方法でこの問題を解決するのでしょうか?

Ousmane D .:

私は最初からマッピングを作成したいTimeDiscount::getIdOfBookTimeDiscount

Map<Long, TimeDiscount> accumulator = 
      actualPromotions.stream()
                     .collect(toMap(TimeDiscount::getIdOfBook, Function.identity()));

それから私はやると思います。

booksToReturn.forEach(e -> {
       TimeDiscount timeDiscount = accumulator.get(e.getIdOfBook());
       if (timeDiscount != null) e.setDiscountRate(e.getDiscountRate() + timeDiscount.getDiscountRate());
});

またはあなたが使用して滞在したい場合はOptional、いくつかの理由があります。

booksToReturn.forEach(e -> 
       Optional.ofNullable(accumulator.get(e.getIdOfBook()))
          .ifPresent(p -> e.setDiscountRate(e.getDiscountRate() + p.getDiscountRate()))
);

これは非効率的に検索を改良actualPromotions.stream()の各要素についてbooksToReturn

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=173628&siteId=1