在这个具体的例子中,根本不需要做中间存储:
Map<T, V> transform(List<T> item) {
return item.stream().collect(toMap(x -> x, x -> doTransform(x)));
}
但如果您需要,Java 9 提供了一种更简单的工厂方法,
Map<T, V> transform(List<T> item) {
return item.stream()
.map(x -> Map.entry(x, doTransform(x)))
.collect(toMap(x -> x.getKey(), x -> x.getValue()));
}
只要你不必与null打交道。
这里可以使用匿名内部类,
Map<T, V> transform(List<T> item) {
return item.stream()
.map(x -> new Object(){ T t = x; V v = doTransform(x); })
.collect(toMap(x -> x.t, x -> x.v));
}
但效率较低。它是一个内部类,它捕获对周围this 的引用,它还捕获x,因此您有两个字段,t 和用于捕获x 的合成字段,用于同一件事。
后者可以通过使用方法来规避,例如
Map<T, V> transform(List<T> item) {
return item.stream()
.map(x -> new Object(){ T getKey() { return x; } V v = doTransform(x); })
.collect(toMap(x -> x.getKey(), x -> x.v));
}
但这并没有增加可读性。
唯一真正的匿名类型是为 lambda 表达式生成的类型,它们可用于通过高阶函数存储信息:
Map<T, V> transform(List<T> item) {
return item.stream()
.map(x -> capture(x, doTransform(x)))
.collect(HashMap::new, (m,f) -> f.accept(m::put), HashMap::putAll);
}
public static <A,B> Consumer<BiConsumer<A,B>> capture(A a, B b) {
return f -> f.accept(a, b);
}
但是,如果您在更复杂的场景中尝试这样做,您很快就会遇到 Java 类型系统的限制(它仍然不是一种函数式编程语言)。