O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

You can create and pass around an implementation of any functional interface as you do with any object. For example, let's write a method that creates Function<Integer, Double>:

Function<Integer, Double> createMultiplyBy10(){  Function<Integer, Double> ourFunc = new Function<Integer, Double>(){    public Double apply(Integer i){ return i * 10.0; }  };  return ourFunc;}

Better yet, we can create a generic method that uses the following:

Function<Integer, Double> createMultiplyBy(double num){  Function<Integer, Double> ourFunc = new Function<Integer, Double>(){    public Double apply(Integer i){ return i * num; }  };  return ourFunc;}

Now we can write this:

Function<Integer, Double> multiplyBy10 = createMultiplyBy(10d);System.out.println(multiplyBy10.apply(1)); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required