简体   繁体   中英

Cast context of functional interface in lambda expression

There's an example of casting a functional interface (as I understand it) in a cast context : https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

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

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context" .

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example? I've tried this:

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

but it works without (ToIntFunction) . When do I need the cast context anyway?

Also what is the purpose of mapToInt . This seems to be equivalent:

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

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

Cast context it means that Java Compiler will auto convert functional interface to the target functional interface type,

As (ToIntFunction) d -> d.intValue() , the compiler will auto convert it to: ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue()

so:

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

it's equal to:

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

And for:

dlist.stream().mapToInt(Double::intValue).forEach(System.out::println);
dlist.stream().map(Double::intValue).forEach(System.out::println);
  • mapToInt 's Double::intValue compiler will convert it to ToIntFunction<Double> .
  • map 's Double::intValue compiler will convert it to Function<Double, Int>

mapToInt is used to return a stream of int primitive type, which could have performance benefits over a stream of Integer. The same is true for the toIntFunction , which returns a function of int primitive type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM