[英]Transform `Arrays.stream(…).collect(…)` from Java 8 to Java 7
[英]Java stream - collect, transform and collect
我想获取 map 的值并找到最小值并为 map 的每个条目构造一个新的 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 +
'}';
}
}
我觉得这可以通过重构和隐藏数据片段来简化,而不是使用收集器进行过度工程。
private static BiFunction<Map<String, Integer>, Integer, List<MyNode>> getListOfMyNodeWithMinValue =
(map, minValue) ->
map.entrySet().stream()
.map(entry -> new MyNode(entry.getKey(), entry.getValue(), minValue))
.collect(Collectors.toList());
public static Function<Map<String, Integer>, List<MyNode>> getMyNodes =
map -> getListOfMyNodeWithMinValue.apply(map, Collections.min(map.values()));
此后可以将其用作MyNode.getMyNodes.apply(inputMap)
。
忽略我的命名约定。 随便输入我的感受。 希望你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.