Sunday, August 27, 2017

Java 8 - Method reference


Last article , I have talked about an interface called Predicate<T> with a return type as boolean. Actually, there are 7 types of interfaces in java 8 predefined .

 Use Case
  Example
 Interfaces
Boolean Expression
(List<String> list) ->list.isEmpty() 
Predicate<List<String>>
New Object
() -> new Apple(10)
Supplier<Apple>
Consume Object
(Apple a) -> System.out.println(a.getWeight())
Consumer<Apple>
Retrieve from Object
(String s) -> s.length()
Function<String, Integer>  / ToIntFunction<String>
Combine 2 values
(int a, int b) -> a * b
IntBinaryOperator
Compare 2 Objects
(Apple a1, Apple a2) ->
a1.getWeight().compareTo(a2.getWeight())
Comparator<Apple> / BiFunction<Apple, Apple, Integer> / ToIntBiFunction<Apple, Apple>



Well, except for those interface above, I think most people have already known the static & instance method calling in java 8 is using :: symbol , for example :

(Apple a) -> a.getWeight()          Apple::getWeight
() -> Thread.currentThread().dumpStack()            Thread.currentThread()::dumpStack
(str, i) -> str.substring(i)      String::substring
(String s) -> System.out.println(s)      System.out::println

But the :: symbol can also be used for creating new Object which is called method reference :

Supplier<Apple> c1 = Apple::new;
Apple a1 = c1.get();

//== 

Supplier<Apple> c1 = () -> new Apple();
Apple a1 = c1.get();

If Apple's Constructor signature is Apple(Integer weight),then Function should be used :

Function<Integer, Apple> c2 = Apple::new;
Apple a2 = c2.apply(110);

//== 

Function<Integer, Apple> c2 = (weight) -> new Apple(weight);
Apple a2 = c2.apply(110);

If Apple's Contructor has 2 paramters, then BiFunction should be used :

BiFunction<String, Integer, Apple> c3 = Apple::new; // point to the 2 params constructor
Apple c3 = c3.apply("green", 110); // create a new Apple object

// ==

BiFunction<String, Integer, Apple> c3 =(color, weight) -> new Apple(color, weight);
Apple c3 = c3.apply("green", 110);

So In a word, those interfaces Supplier, Function, BiFunction only create a reference to certain constructors, and the creation of new object is done by those methods get and apply. 

Well, most of the time , 2 params constructor encapsulation is enough , but what if 3,  4 .. params constructors are needed. Just define your interface like this :


public interface TriFunction<T, U, V, R>{
    R apply(T t, U u, V v);
}

And Use it similarly :


TriFunction<Integer, Integer, Integer, Color> colorFactory = Color::new;

Ok, That's all about the method reference. I will cover most of the use cases in later articles.

No comments:

Post a Comment

Add Loading Spinner for web request.

when web page is busily loading. normally we need to add a spinner for the user to kill their waiting impatience. Here, 2 steps we need to d...