どのように2つのリストは、ストリームと1.8の機能を使用して参加することができますか?

AB11:

私が持っているList価格とPriceGroupsのを。

static class PriceGroup {
    String priceName;
    String priceGroup;
}

static class Price {
    String priceName;
    Integer price;
}

以下にいくつかのサンプルデータ、およびIはそれぞれPriceGroupの最安価格を見つける書いた実装があります。任意の提案は、私がこのデータを結合するためのストリームを利用するようにリファクタリングできますか?

List<PriceGroup> priceGroups = Arrays.asList(
        new PriceGroup("F1", "Friends"),
        new PriceGroup("F2", "Friends"),
        new PriceGroup("O1", "Others"),
        new PriceGroup("O2", "Others"));

List<Price> prices = Arrays.asList(
        new Price("F1", 100),
        new Price("F2", 150),
        new Price("O1", 250),
        new Price("O2", 300));

public Map<String, Integer> getBestPrices(List<PriceGroup> priceGroups, List<Price> prices) 
{
    Map<String, Integer> bestPrice = new HashMap<String, Integer>(); 
    for (PriceGroup priceGroup : priceGroups) {
        if (bestPrice.get(priceGroup.priceGroup) == null) {
            bestPrice.put(priceGroup.priceGroup, 10000000);
        }

        for (Price price : prices) {
            if (price.priceName.equals(priceGroup.priceName)) {
                bestPrice.put(priceGroup.priceGroup, Math.min(price.price, bestPrice.get(priceGroup.priceGroup)));
            }
        }
    }

    return bestPrice;
}

与えられたデータのために、私の機能はしてマップを返す必要があります。

F1 => 100
O1 => 250

ルスラン:

2つのリストが参加取得するには、専用のオブジェクトを作成するために考えることができます:

class Joined {
    String priceGroup;
    String priceName;
    Integer price;
    ...

次に、使用してflatMapあなたが参加することができますpriceGroupsへのpricespriceNameでフィールドとグループpriceGroup

Map<String, Optional<Joined>> map = priceGroups.stream()
        .flatMap(group -> prices.stream()
                .filter(p -> p.getPriceName().equals(group.getPriceName()))
                .map(p -> new Joined(group.getPriceGroup(), group.getPriceName(), p.getPrice())))
        .collect(groupingBy(Joined::getPriceGroup, minBy(Comparator.comparing(Joined::getPrice))));

今、あなたが期待される結果を印刷することができますマップから値を取得します:

for (Optional<Joined> value : map.values()) {
        value.ifPresent(joined -> System.out.println(joined.getPriceName() + " " + joined.getPrice()));
    }

// O1 250
// F1 100

おすすめ

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