【发布时间】:2021-03-18 08:26:18
【问题描述】:
我想获取地图的值并找到最小值并为地图的每个条目构造一个新的 CodesWithMinValue 实例。我希望使用 Java 11 流来实现这一点,我可以使用多行中的多个流来实现这一点(一个用于最小值,一个用于转换)。是否可以使用 java 11 流和收集器在一行中实现? 谢谢。
public static void main(String[] args) {
Map<String, Integer> codesMap = getMockedCodesFromUpstream();
var minValue = Collections.min(codesMap.values());
var resultList = codesMap.entrySet().stream()
.map(e -> new CodesWithMinValue(e.getKey(), e.getValue(), minValue))
.collect(Collectors.toUnmodifiableList());
//is it possible to combine above three lines using stream and collectors API,
//and also can't call getMockedCodesFromUpstream() more than once. getMockedCodesFromUpstream() is a mocked implementation for testing.
//TODO: combine above three lines into a single line if possible
System.out.println(resultList);
}
private static Map<String, Integer> getMockedCodesFromUpstream(){
Map<String, Integer> codesMap = new HashMap<>();
codesMap.put("CDXKF", 44);
codesMap.put("GFDFS", 13);
codesMap.put("KUSSS", 10);
codesMap.put("EWSNK", 52);
codesMap.put("IOLHF", 21);
return codesMap;
}
private static class CodesWithMinValue{
public final String code;
public final int value;
public final int minValue;
public CodesWithMinValue(String code, int value, int minValue) {
this.code = code;
this.value = value;
this.minValue = minValue;
}
@Override
public String toString() {
return "CodesWithMinValue{" +
"code='" + code + '\'' +
", value=" + value +
", minValue=" + minValue +
'}';
}
}
【问题讨论】:
标签: java java-stream java-11