Lamba Expression

Buddhika Sandaruwan
4 min readMar 1, 2022

--

Lambda expression is introduced from Java 1.8. Lambda expression lets you pass the “functions” to the code. By using Lambda Expression we can simplify some complex loop/conditional logic or workflow into 1, 2 lines of code.

Main Objective why Java introduce Lambda Expression

The main objective of being introduced Lambda expression in Java 1.8 is to bring out the functional programming features to java. because java is purely 100% OOP. This doesn’t support functional programming at all before java 1.8. But, other OOP languages like python supports functional programming. So Java has introduced Lambda expression in the version of Java 1.8.

What is functional programming?

Functional programming is simply functions and variables. but, when it comes to java as java is an OOP language it has only classes and objects to work with. as Python or any other OOP language that supports functional programming, java has introduced Lambda expressions to java since 1.8 to bring the functions and variables to the java code.

Advantage of Lambda expression

  • Improve the code optimization concisely code. (simplify code)
  • Achieve big tasks in a small way.
  • High efficiency

What is Lambda

Lambda expression is an anonymous function/method.

The anonymous function is,

  • It doesn’t have a name
  • It doesn’t have a return type.
  • No access modifier.

Convert normal method to lambda expression

If we want to mention the data type of the parameter when we are using a lambda expression we can skip the data type in the parenthesis. because JVM in compile-time identifies the data type according to the context.

How to call a Lambda expression

To call a Lambda expression we have to understand the functional interface first.

The functional interface should have only one abstract method. But it can have other concrete methods.

Some default functional interfaces are there in java

  • Runnable — — — — — — — -> run()
  • Callable — — — — — — — ->call()
  • Comparable — — — — — — -> comparaTo()
  • ActionListener — — — — — -> actionPerfoomed()

We can only call the lambda expression using functional interface.

@FunctionalInterface

If we use this annotation for a interface. It consider the interface as functional interface. and gives compile error if some wrong things happens.

When we developing an application we may not have to write functional interface always. Writing functional interface always is not good approach in programming. So that in java has given some pre defined functional interfaces for our usage.

Sample using lambda expression

public interface Dog {
void bark(String name, String address);
}class Demo {
public static void main(String[] args) {
/* type of the variable is not mandetory JVM get the type automatically according to the context
* So we can remove String type from the lambda expression. */
Dog bullDog = (name, address) -> System.out.println(name +" is living in "+address);
bullDog.bark("Sachintha","Kottawa");
}
}

Pre define functional interfaces

  • Predicate
  • Function
  • Consumer
  • Supplier

All these functional interfaces are in java.util.function package.

Predicate functional interface

this simply returns true or false according to the input. The predicate is an interface that has only a method (abstract method) named test(), and it takes one argument(any data type) and returns a boolean.

@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);}

Only if we have a conditional check we can go for Predicate.

example,

public class Demo1 {
public static void main(String[] args) {
/* In this Predicate interface mainly getting a any type of value and return true and false */
Predicate<Integer> p = i -> (i < 10); /* i eka wishalada balanawa 10ta wada*/
System.out.println(p.test(10)); /* this functional interface has only one method called test(T t)*/
System.out.println("--------------------------------------------------------------------");
/* Predicate interface takes only one parameter*/
Predicate<String[]> p1 = s -> (s.length > 2);
String a[] = {"s", "b", "e"};
System.out.println(p1.test(a));
System.out.println("-----------------------------------------------------------------------");
Predicate<String> p2 = j -> (j.length() < 4);
System.out.println(p2.test("Sachihthasfaa"));
System.out.println("-----------------------------------------------------------------------");
/* We are checking given array element is greater than 4*/
String names[] = {"Sachintha","Uditha","Harsha","Charith","Tom","Jim","John"};
for (String name : names){
if (p2.test(name)){
System.out.println("Length is less than 4 :"+name);
}
}
}
}

Function functional interface

It has apply() method in function interface that can takes any number of arguments and return a single value.

@FunctionalInterface
public interface Function<T, R> { R apply(T t);}

example,

class Employee {
String name;
int sal;
public Employee(String name, int sal) {
this.name = name;
this.sal = sal;
}
}
public class Demo1 {
public static void main(String[] args) {
List<Employee> list = new ArrayList<>();
list.add(new Employee("Sachintha",1000));
list.add(new Employee("Uditha",4733));
list.add(new Employee("Charitha",9000));
list.add(new Employee("Harsha",5300));
Function<Employee,Integer> fn = i -> {
if (i.sal > 4000 && i.sal < 5500) {
return (i.sal * 10/100) + i.sal;
}
return 0;
};
Predicate<Integer> p = i -> i > 4000; for (Employee e : list){
if (p.test(e.sal)){
int a = fn.apply(e);
System.out.println(a);
}
}
}
}

Consumer functional interface

The consumer interface doesn’t return anything, it just use the input that user gives. It has the method called accept();

@FunctionalInterface
public interface Consumer<T> {
void accept(T t);}

example,

public class Java8Consumer1 {    public static void main(String[] args) {        Consumer<String> print = x -> System.out.println(x);
print.accept("java"); // java
}}

--

--