私のやり方 :
私は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
からactualPromotions
にdiscountRate
から値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::getIdOfBook
にTimeDiscount
:
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
。