() -> Single Statement or Expression;
() -> { <Multiple Statements> };
@FunctionalInterface
package com.learnJava.lambdas;
public class RunnableLambdaExample {
public static void main(String[] args) {
/**
* prior Java 8
*/
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Inside Runnable 1");
}
};
new Thread(runnable).start();
/**
* Java 8 lambda
*/
Runnable runnableLambda = () -> {
System.out.println("Inside Runnable 2");
};
Runnable runnableLambda1 = () -> {
System.out.println("Inside Runnable 3");
System.out.println("Inside Runnable 3");
};
new Thread(runnableLambda).start();
new Thread(runnableLambda1).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Inside Runnable 3.1");
}
}).start();
// most simplest way
new Thread(() -> System.out.println("Inside Runnable 4")).start();
}
}
package com.learnJava.lambdas;
import java.util.Comparator;
public class ComparatorLambdaExample {
public static void main(String[] args) {
/**
* prior java 8
*/
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2); // 0 -> o1 == 02
// 1 -> o1 > o2
// -1 -> o1 < o2
}
};
System.out.println("Result of the comparator is : " + comparator.compare(3, 2));
Comparator<Integer> comparatorLambda = (Integer a, Integer b) -> a.compareTo(b);
System.out.println("Result of the comparator using Lambda is : " + comparatorLambda.compare(3, 2));
Comparator<Integer> comparatorLambda1 = ( a, b) -> a.compareTo(b);
System.out.println("Result of the comparator using Lambda is : " + comparatorLambda.compare(3, 2));
}
}