lambda - 如何在 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();
}
}
希望我能够解释问题陈述。如果这个问题有更好的解决方案,请告诉我。在此先感谢您的帮助。
解决方案
推荐阅读
- java - 构建发布构建的签名 APK 失败,但调试成功。缺课
- html - 我想用 html 和 css 解决所有这些评估
- jquery - Moment.js:时间不基于计算机时间
- r - R Markdown 2列应该具有相同的名称
- android - 如何获取firebase中元素的关键?
- javascript - 两个 div 问题之间的滚动延迟
- tensorflow - 在 jupyter notebook 中运行训练有素的 kaggle 模型
- flutter - 如何同时使用 Firebase Auth 和 Facebook 登录?
- r - 比较数据框中的所有行并有条件地应用函数
- java - 如何在 JTextField 中排列二维数组的值