如何重写这种旧式代码以使用Java 8流?我知道可以使用一行流代码来完成。
Map<String, ImmutablePair<Double, Double>> dataCache = new LinkedHashMap<>()
List<Map<String, Object>> data = new ArrayList<>();
for(Map<String, Object> rec : data) {
String code = (String) rec.get("code");
Double x0 = (Double) rec.get("x0");
Double x1 = (Double) rec.get("x1");
dataCache.put(code, new ImmutablePair<>(x0, x1));
}
本质上,我们的想法是将一般记录列表重新映射到更结构化的哈希查找中。
答案 0 :(得分:3)
Map<String, ImmutablePair<Double, Double>> dataCache = data.stream()
.collect(
Collectors.toMap(
rec -> (String) rec.get("code"),
rec -> new ImmutablePair<>(
(Double) rec.get("x0"), (Double) rec.get("x1"))));
如果你关心地图实现,你可能想要
Map<String, ImmutablePair<Double, Double>> dataCache = data.stream()
.collect(
Collectors.toMap(
rec -> (String) rec.get("code"),
rec -> new ImmutablePair<>(
(Double) rec.get("x0"), (Double) rec.get("x1")),
(p1, p2) -> { throw new IllegalArgumentException(); },
LinkedHashMap::new));
答案 1 :(得分:3)
由于您需要一个行的流代码:
Map<String, ImmutablePair<Double, Double>> dataCache = data.stream().collect(Collectors.toMap(rec -> (String) rec.get("code"), rec -> new ImmutablePair<>((Double) rec.get("x0"), (Double) rec.get("x1")), (a, b) -> b, LinkedHashMap::new));