Thursday, February 9, 2017

Java 8 Lambda Expressions

I'll try to explain the topic according to my motto --"No bullshit , Just Code.."

1) SAM= Single Abstract Method = An Interface with Only One Method = Functional Interface

@FunctionalInterface
public interface StateChangeListener {
public String onStateChange(State oldState, State newState);
}
view raw sam hosted with ❤ by GitHub
2) A class with a method which will consume a lambda expression

public class StateManager {
public void addNewStateListener(StateChangeListener listener) { //blahh }
}
view raw LamdbaConsumer hosted with ❤ by GitHub
3) Now.. Actionnn...Lambda expression as a parameter

StateManager stateManager = new StateManager();
stateManager.addNewStateListener(
(oldState, newState) -> System.out.println("State changed")
);




Okeyy... I know some of you need bullshit also :)

If you want to pass a behavior to a parameter (behavior= function=action) just create an interface and annotate it @FunctionalInterface and use Lambda Syntax like i did in above.

(param1,param2,,,,,paramN) -> {play with params}

Java 8 lots of built in @FunctionalInterface inside it. You can use them anywhere you need. Just  google for them .

Bye

No comments:

Post a Comment