Lambda expressions in Java 8 are very powerful and therefore very compelling. Here are just a few of the key benefits to using lambda expressions in Java:
- Conciseness
- Reduction in code bloat
- Readability
- Elimination of shadow variables
- Encouragement of functional programming
- Code reuse
- Enhanced iterative syntax
- Simplified variable scope
- Less boilerplate code
- JAR file size reductions
- Parallel processing opportunities
In this post, you can see how in few lines we can finish code to print numbers alternatively by Two threads.
import java.util.stream.IntStream;
public class EvenOddThreadLambdaDemo {
static Integer number = new Integer(1);
static Object LOCK = new Object();
public static void main(String[] args) {
IntStream.range(0, 2).forEach(i -> new Thread(() -> {
printNumbers();
}).start());
}
public static void printNumbers() {
while (EvenOddThreadLambdaDemo.number " + EvenOddThreadLambdaDemo.number++);
LOCK.notify();
try {
// let's not eat CPU if work is done.
LOCK.wait(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/*
Odd--> 1
Even--> 2
Odd--> 3
Even--> 4
Odd--> 5
Even--> 6
Odd--> 7
Even--> 8
Odd--> 9
Even--> 10
Odd--> 11
Even--> 12
Odd--> 13
Even--> 14
Odd--> 15
Even--> 16
Odd--> 17
Even--> 18
Odd--> 19
Even--> 20
*/