Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of Lambda expression in java 8

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 136
    Comment on it

    The lambda expressions is introduced in java 8 and easy to use. Lamda expression automatically read the params type and return the same type value.

    Like we have an anonymous class to implement some listener in it like this :

    button.addTouchListener(new TouchListener() {
        public void touch(TouchEvent e) { 
           System.out.println("Touch event fire.");
        }
    });
    

    But this is getting old now by using lambda expression we can define this in a single line like this

    button.addTouchListener(e -> System.out.println("Touch event fire."));

    where e is the parameter and -> is lambda expression that separate the body from parameter.

    Below is the example of Lambda expression use -

    public class LambdaExample {
        public static void main(String args[]){
            LambdaExample tester = new LambdaExample();
    
            CommonOperations addition = (a, b) -> a + b;
    
            CommonOperations subtraction = (a, b) -> a - b;
    
            CommonOperations multiplication = (a, b) ->  a * b };
    
            CommonOperations division = (a, b) -> a / b;
    
            System.out.println("5 + 5 = " + tester.perform(10, 5, addition));
            System.out.println("10 - 5 = " + tester.perform(10, 5, subtraction));
            System.out.println("15 x 5 = " + tester.perform(10, 5, multiplication));
            System.out.println("40 / 5 = " + tester.perform(10, 5, division));
    
        }
    
        interface CommonOperations {
            int operation(int a, int b);
        }
    
        private int perform(int a, int b, CommonOperations commonOperations){
            return commonOperations.operation(a, b);
        }
    }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: