在强制转换上下文中投射功能界面(我理解)的示例:https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html带有代码示例:
// Cast context
stream.map((ToIntFunction) e -> e.getSize())...
它被描述为"功能接口可以在多个上下文中提供目标类型,例如赋值上下文,方法调用或强制转换上下文" 。
我已尝试将ToIntFunction
与stream().mapTo()
一起使用,但只能与stream().mapToInt()
一起使用,也不能使用演员。
有人可以提供一个如何使用强制转换上下文示例的示例吗? 我试过这个:
// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)
但没有(ToIntFunction)
。我什么时候需要演员上下文?
mapToInt
的目的是什么?这似乎是等价的:
dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);
dlist.stream().map(d -> d.intValue()).forEach(System.out::println);
答案 0 :(得分:3)
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);
mapToInt
的{{1}}编译器会将其转换为Double::intValue
。ToIntFunction<Double>
的{{1}}编译器会将其转换为map
答案 1 :(得分:0)
>>> a = [2,4,5,2]
>>> min_value = min(a)
>>> [i for i, x in enumerate(a) if x == min_value]
[0, 3]
用于返回int基本类型的流,这可能比Integer流具有性能优势。
mapToInt
也是如此,它返回int基本类型的函数。