在 lambda 表达式中转换功能接口的上下文

Cast context of functional interface in lambda expression

有一个在 cast context 中转换功能接口(据我了解)的示例:https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html 带有代码示例:

 // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...

描述为"Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

我尝试将 ToIntFunctionstream().mapTo() 一起使用,但只能将其与 stream().mapToInt() 一起使用,也无法使用强制转换。

有人可以提供一个如何使用强制转换上下文示例的示例吗? 我试过这个:

// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

但没有 (ToIntFunction) 也能正常工作。我什么时候需要 cast context

还有mapToInt的目的是什么。这似乎是等价的:

dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);

mapToInt 用于 return int 原始类型的流,它可能比 Integer 流具有性能优势。 toIntFunction也是如此,return是int原始类型的函数。

Cast context 这意味着 Java 编译器 将自动将 functional interface 转换为目标 functional interface 类型,

作为(ToIntFunction) d -> d.intValue(),编译器会自动将其转换为:ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue()

所以:

dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

等于:

ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue();
dlist.stream().mapToInt(toIntFunction).forEach(System.out::println);

还有:

dlist.stream().mapToInt(Double::intValue).forEach(System.out::println);
dlist.stream().map(Double::intValue).forEach(System.out::println);
  • mapToIntDouble::intValue 编译器会将其转换为 ToIntFunction<Double>.
  • mapDouble::intValue 编译器会将其转换为 Function<Double, Int>