Java 8 is the update that completely changed how Java developers write code. It took Java from “old-school, verbose, class-heavy” to clean, modern, expressive.
Today we starts with LAMBDA EXPRESSION(Part-1)
In Java, writing even a small piece of logic used to be lengthy because we had to create an anonymous class and override its method every single time. Java 8 solved this problem by introducing lambda expressions — a short, clean, functional‑style way to write code.
Basic Syntax
(parameters)−>body
Variations
No parameter- ()->System.out.println("HI");
One parameter-x->x*x;
Multiple parameter- (x,y)->x*y;
// with blocks with parameter return is must
With Blocks- x->{int y=x+1; return y;};
// with blocks with void return is no need
with Blocks with void- ()->{ system.out.println("HI"); }
Before 8:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Running");
}
}).start();
After 8:
new Thread(() -> System.out.println("Running")).start();
Capturing variables
Rule: Variable must be “effectively final”
int processedCount = 0;
orders.forEach(order -> {
processedCount++; // ❌ ERROR
});
Local variable processedCount defined in an enclosing scope must be final or effectively final
How to fix,
Fix 1: Use AtomicInteger
AtomicInteger processedCount = new AtomicInteger(0);
orders.forEach(order -> {
processedCount.incrementAndGet(); // ✔ Works
});
Atomic Integer is an object.
Java allows change the variable
Because Object reference is final but we change the values.
AtomicInteger sum = new AtomicInteger(0);
list.forEach(n -> sum.addAndGet(n));
System.out.println(sum.get());
Fix 2: Use array wrapper
int[] processedCount = {0};
orders.forEach(order -> {
processedCount[0]++; // ✔ Works
});
Any reference is final we change their values so we can do
Fix 3: Use Stream count
long processedCount = orders.stream().count();
Hope this helped you understand Java 8 better.
In the next blog, we dive into another Java 8 Topic—don’t miss it!
Top comments (2)
Nice akka ...
thank you brother..