(parameters) -> expression (parameters) -> { // block of code }
Class::methodname Object::methodname
@FunctionalInterface public interface Printable<T> { void print(T v); default void printLine(int size) { for(int i =1; i <=size; i ++) System.out.print('-'); } }
// Anonymous inner class example Printable<String> p1 = new Printable<String>() { @Override public void print(String v) { System.out.println(v); } }; p1.print("Anonymous Inner Class");
Printable<String> p2 = (String v) -> System.out.println(v); p2.print("Lambda expression");
Printable<String> p2 = (v) -> System.out.println(v); p2.print("Lambda expression");
Printable<String> p3 = System.out::println; p2.print("Lambda Expression With Method Reference");
public class MultiThreadingJava7 { public static void main(String[] args) { Runnable task = new Runnable() { public void run() { for (int i=1;i <=10; i++) System.out.println(i); } }; Thread t = new Thread(task); t.start(); } }
public class MultiThreadingJava8 { public static void main(String[] args) { Runnable task = () -> { for (int i=1;i <=10; i++) System.out.println(i); }; Thread t = new Thread(task); t.start(); } }
public class MyTime { private int hours, mins, secs; public MyTime(int hours, int mins, int secs) { this.hours = hours; this.mins = mins; this.secs = secs; } @Override public String toString() { return String.format("%02d:%02d:%02d", hours, mins, secs); } public int totalSeconds() { return hours * 3600 + mins * 60 + secs; } }
import java.util.ArrayList; public class LambdaWithMyTime { public static void main(String[] args) { ArrayList<MyTime> times = new ArrayList<MyTime>(); times.add( new MyTime(10,34,30)); times.add( new MyTime(14,15,20)); times.add( new MyTime(7,10,50)); // sort times with Lambda expression times.sort((t1,t2) -> t1.totalSeconds() - t2.totalSeconds()); times.forEach(t -> System.out.println(t)); // using lambda expression times.removeIf(t -> t.totalSeconds() > 3600); } }
removeIf(Predicate<T>) forEach(Consumer<T>)