Java 8 Features

Lambdas and Functional Interfaces:

Java 8 introduced a game-changing feature called lambdas, enabling the expression of functional-style programming in Java. Lambdas are anonymous functions that allow concise and expressive code. They work seamlessly with functional interfaces, which are interfaces with a single abstract method.

Example of Using Lambdas and Functional Interfaces:

// Functional Interface
interface MathOperation {
int operate(int a, int b);
}

// Lambda Expression
MathOperation addition = (a, b) -> a + b;
MathOperation subtraction = (a, b) -> a – b;

// Usage
int result1 = addition.operate(10, 5); // Output: 15
int result2 = subtraction.operate(10, 5); // Output: 5

Streams and Stream Operations:

Java 8 introduced the Stream API, which allows processing collections of data in a functional and declarative manner. Streams enable developers to perform operations like filtering, mapping, and reducing elements effortlessly.

Example of Using Streams:

List<String> fruits = Arrays.asList(“Apple”, “Banana”, “Orange”, “Mango”);

fruits.stream()
.filter(fruit -> fruit.length() > 5)
.map(String::toUpperCase)
.forEach(System.out::println);
// Output: BANANA
// ORANGE

Default Methods in Interfaces:

With Java 8, interfaces can now have default methods, which are methods with an implementation in the interface itself. This feature allows adding new methods to interfaces without breaking the implementation of existing classes that implement the interface.

Example of Default Method in Interface:

interface Vehicle {
void start();

void stop();

default void honk() {
System.out.println(“Honking the horn!”);
}
}

class Car implements Vehicle {
public void start() {
System.out.println(“Car started”);
}

public void stop() {
System.out.println(“Car stopped”);
}
}

// Usage
Car car = new Car();
car.start(); // Output: Car started
car.stop(); // Output: Car stopped
car.honk(); // Output: Honking the horn!

Conclusion:

Java 8 features have revolutionized the way we write Java code, bringing functional programming capabilities and enhanced expressiveness. Lambdas and functional interfaces enable cleaner, more concise code, while Streams streamline data processing. Default methods in interfaces provide better backward compatibility when evolving interfaces. Embrace Java 8 features in your projects, and witness the power of modern Java programming!

Leave a Comment