首页 > 解决方案 > 如何在 groupingBy 后排序并选择排序列表中的第一个元素

问题描述

问题陈述:假设我有PriceRow(productCode, key, sector)对象列表

        List<PriceRow> priceRowList = new ArrayList<>();
        priceRowList.add(new PriceRow("10kgbag","", "SECTOR"));
        priceRowList.add(new PriceRow("10kgbag","12345", ""));
        priceRowList.add(new PriceRow("10kgbag","", ""));
        priceRowList.add(new PriceRow("20kgbag","", "SECTOR"));
        priceRowList.add(new PriceRow("20kgbag","12345", ""));
        priceRowList.add(new PriceRow("20kgbag","", ""));
        priceRowList.add(new PriceRow("30kgbag","", "SECTOR"));
        priceRowList.add(new PriceRow("30kgbag","", ""));
        priceRowList.add(new PriceRow("40kgbag","", ""));
        priceRowList.add(new PriceRow("50kgbag","", ""));

现在,我需要按productCode对其进行分组,然后根据第一个然后扇区对其进行排序,如果两行都不可用,则使用(key = blank) 和 (sector=blank)的行,现在取第一个排出排序列表以创建一个Map<String, PriceRow)

因此最终的断言应该看起来像

assertEquals("12345",map.get("10kgbag").getFlightKey());
assertEquals("12345",map.get("20kgbag").getFlightKey());
assertEquals("SECTOR",map.get("30kgbag").getSector());  
assertEquals("",map.get("40kgbag").getFlightKey());     
assertEquals("",map.get("50kgbag").getFlightKey());

我想出的解决方案是

import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Example {
    public Map<String,PriceRow> evaluate(List<PriceRow> priceRowList) {
        Map<String,PriceRow>  map =  priceRowList.stream()
                .collect(Collectors.groupingBy(priceRow -> priceRow.getProductCode(),
                        Collectors.collectingAndThen(Collectors.toList(), value -> getMostEligibleValue(value))));
        return map;
    }


    private PriceRow getMostEligibleValue(List<PriceRow> priceRowList){
        for(PriceRow priceRowWithKey : priceRowList)
            if(StringUtils.isNotBlank(priceRowWithKey.getKey()))
                return priceRowWithKey;

        for(PriceRow priceRowWithSector : priceRowList)
            if(StringUtils.isNotBlank(priceRowWithSector.getSector()))
                return priceRowWithSector;

        return priceRowList.stream().findFirst().get();
    }
}

希望我能够解释问题陈述。如果这个问题有更好的解决方案,请告诉我。在此先感谢您的帮助。

标签: lambdajava-8

解决方案


推荐阅读