Java 8 API examples using lambda expressions and functional programming. Example 1: The java.lang.Runnable interface has been made a functional interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.java8.examples; public class Example1 { public static void main(String[] args) { System.out.println("main thread: " + Thread.currentThread().getName()); //run method takes no arguments so: () -> (body) //closure worker thread1 Runnable r = () -> (System.out.println("worker thread: " + Thread.currentThread().getName())); new Thread(r).start(); //pass the Runnable closure to Thread constructor //closure worker thread2 new Thread( () -> (System.out.println("worker thread: " + Thread.currentThread().getName()))).start(); } } |
Output: main thread: main worker thread: Thread-0 worker thread: Thread-1 Example 2: The java.util.function package has a number…