Java 8 Lambda Expressions PRO

When dealing with an interface that includes one method only and the sole purpose of that interface is to allow us passing over functionality to another part of our program we can use the lambda expression as an alternative for the anonymous inner class.

The lambda expression includes a comma separated list of formal parameters enclosed within parentheses (the data type of the parameters can be usually omitted). If there is only one parameter then we can omit the parentheses.

ob -> ob.age<40

The body includes a single expression or a statement block. We can include the return statement. Unless the method signature doesn’t include the void return value then we must place the code of the body within curly braces.

The following code sample is a simple demo for using Java 8 lambda expressions. This code sample uses a lambda expression as an alternative for defining and instantiating a new inner class (most likely an anonymous one) that implements MathOperation.

package com.lifemichael.samples;

public class SimpleLambdaExpressionDemo {
    interface MathOperation {
        int execute(int a, int b);
    }
    public int calculate(int a, int b, MathOperation op) {
        return op.execute(a, b);
    }
    public static void main(String... args) {
        SimpleLambdaExpressionDemo myApp =
                new SimpleLambdaExpressionDemo();
        MathOperation addition = (a, b) -> a + b;
        MathOperation subtraction = (a, b) -> a - b;
        int num = addition.execute(40, 2);
        System.out.println("40 + 2 = " + num);
        System.out.println("20 – 10 = " +
                myApp.calculate(20, 10, subtraction));
    }
}

The following video clip goes over this code sample, overviews it, shows its execution and explains it step by spte.

We can refer a static method by specifying the name of the class following with “::” and the name of the static method. The following code sample shows how to do it.

package com.lifemichael.samples;

public class SimpleLambdaExpressionDemo {
    interface MathOperation {
        int execute(int a, int b);
    }
    public static void main(String... args) {
        SimpleLambdaExpressionDemo myApp =
                new SimpleLambdaExpressionDemo();
        MathOperation op = Utils::calcu;
        int num = op.execute(40, 2);
        System.out.println("40 * 2 = " + num);
    }
}
class Utils
{
    public static int calcu(int a,int b)
    {
        return a*b;
    }
}

The following video clip goes over this code sample, shows its execution and explains it step by step.

We can refer a specific instance method by specifying the reference for the object following with “::” and the name of the instance method. The following code sample shows how to do it.

package com.lifemichael.samples;

public class SimpleLambdaExpressionDemo {
    interface MathOperation {
        int execute(int a, int b);
    }
    public static void main(String... args)
    {
        SimpleLambdaExpressionDemo myApp =
                new SimpleLambdaExpressionDemo();
        Utils utils = new Utils();
        MathOperation op = utils::calcu;
        int num = op.execute(40, 2);
        System.out.println("40 * 2 = " + num);
    }
}
class Utils
{
    public int calcu(int a,int b)
    {
        System.out.println("calcu is called");
        return a*b;
    }
}

The following video clip goes over this code sample, shows its execution and explains it step by step.

We can refer a specific instance method without been specific about the object on which it should be invoked. Instead of specifying the reference for a specific object we should specify the name of the class followed by :: and the name of the function. The following code sample shows how to do it.

import java.util.*;

public class SimpleLambdaExpressionDemo {
    public static void main(String... args) {
        Student[] students = {
                new Student(123123,98,"dave"),
                new Student(234233,88,"ron"),
                new Student(452343,82,"ram"),
                new Student(734344,64,"lara")
        };
        Arrays.sort(students,Student::compareTo);
        for(Student std : students) {
            System.out.println(std);
        }
    }
}

class Student implements Comparable<Student>
{
    private double average;
    private int id;
    private String name;
    Student(int id, double avg, String name)
    {
        this.average = avg;
        this.id = id;
        this.name = name;
    }
    @Override
    public String toString() {
        return id+" "+average+" "+name;
    }
    @Override
    public int compareTo(Student o) {
        if(this.average>o.average) {
            return 1;
        }
        else if(this.average<o.average) {
            return -1;
        }
        else return 0;
    }
}

The following video clip overviews this code sample, shows its execution and explains it step by step.

We can refer the default constructor in a class by writing the name of the class following with ::new. Doing so can be an alternative for defining and instantiating a new class that implements an interface with one method.. a method that has no parameters and its returned value is a reference for a new object instantated using the default constructor we are referring to. The following code sample shows how to do it.

package com.lifemichael.samples;

public class ReferenceToConstructor
{

    public static void main(String... args)
    {
        Student []students = new Student[8];
        populate(students, Student::new);
        for(int i=0; i<students.length; i++)
        {
            System.out.println(students[i]);
        }
    }

    public static void populate(Student[] vec, StudentsGenerator ob)
    {
        for(int i=0; i<vec.length; i++) {
            vec[i] = ob.create();
        }
    }
}

interface StudentsGenerator
{
    public Student create();
}

class Student implements Comparable<Student>
{
    private static int counter = 1;
    private static String[] names = {"david","moshe","anat","jake"};
    private double average;
    private int id;
    private String name;

    Student()
    {
        id = counter++;
        name = names[(int)(names.length*Math.random())];
        average = (int)(100*Math.random());
    }

    Student(int id, double avg, String name)
    {
        this.average = avg;
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString()
    {
        return id+" "+average+" "+name;
    }

    @Override
    public int compareTo(Student o)
    {
        if(this.average>o.average)
        {
            return 1;
        }
        else if(this.average<o.average) {
            return -1;
        }
        else return 0;
    }
}

The following video clip goes over this code sample, shows its execution and explains it step by step.

You can find more video clips, more code samples and more training material in my free courses web site at http://abelski.lifemichael.com.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

NoSQL Databases Courses, Seminars, Consulting, and Development

MongoDB Design Patterns Meetup

The use of MongoDB involves with various cases in which we can overcome performance issues by implementing specific design patterns.

image of woman and database

Record Classes in Java

Learn how to define record classes in Java, and when to use record classes in your code. Stay up to date with the new Java features.

Accessibility | Career | Conferences | Design Patterns | JavaScript | Meetups | PHP | Podcasts | Python | Self Learning

Teaching Methodologies | Fullstack | C++ | C# | CSS | Node.js | Angular | Java | Go | Android | Kotlin | Swift | Academy

Front End Development | Scala | Architectures | Cloud | Big Data | Internet of Things | Kids Learn Programming

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Skip to content Update cookies preferences