Lambdas Expression Java 8

One issue about anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, the syntax of anonymous classes may seem too unwieldy and unclear. In these cases, you’re usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

public class Calculator {

interface IntegerMath {
 int operation(int a, int b);
 }

public int operateBinary(int a, int b, IntegerMath op) {
 return op.operation(a, b);
 }

public static void main(String… args) {

Calculator myApp = new Calculator();
 IntegerMath addition = (a, b) -> a + b;
 IntegerMath subtraction = (a, b) -> a – b;
 System.out.println(“40 + 2 = ” +
myApp.operateBinary(40, 2, addition));
 System.out.println(“20 – 10 = ” +
myApp.operateBinary(20, 10, subtraction));
 }
 }

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s