DEV Community

Cover image for Java-8 (The Biggest Transformation)
s mathavi
s mathavi

Posted on

Java-8 (The Biggest Transformation)

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();
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode
  • 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());

Enter fullscreen mode Exit fullscreen mode

Fix 2: Use array wrapper

int[] processedCount = {0};

orders.forEach(order -> {
    processedCount[0]++;   // ✔ Works
});
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
ranjith_ranjith_6851c8e0a profile image
Ranjith Ranjith

Nice akka ...

Collapse
 
s_mathavi_2fa1e3ea8514f34 profile image
s mathavi

thank you brother..