Java 8 New Features

Java 8 New Features

Java 8 introduced several new features that made Java more powerful and flexible. This article covers some of the most important features introduced in Java 8.

Lambda Expressions

Lambda expressions provide a clear and concise way to represent one method interface using an expression. They allow you to treat functionality as a method argument, or treat a code as data.


List names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
      

Stream API

The Stream API allows you to process sequences of elements in a functional style. It provides methods for filtering, mapping, and reducing data.


List names = Arrays.asList("Alice", "Bob", "Charlie");
List upperCaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());
upperCaseNames.forEach(System.out::println);
      

Functional Interfaces

Functional interfaces are interfaces with a single abstract method. They provide target types for lambda expressions and method references.


@FunctionalInterface
interface MyFunctionalInterface {
    void display();
}

public class Main {
    public static void main(String[] args) {
        MyFunctionalInterface msg = () -> System.out.println("Hello, this is a lambda expression.");
        msg.display();
    }
}
      

Default Methods

Default methods allow you to add new methods to interfaces without breaking the existing implementations. They provide a way to specify behavior that can be inherited by classes.


interface MyInterface {
    default void display() {
        System.out.println("This is a default method.");
    }
}

public class Main implements MyInterface {
    public static void main(String[] args) {
        Main obj = new Main();
        obj.display();
    }
}
      

Optional Class

The Optional class provides a container object which may or may not contain a non-null value. It is used to avoid null checks and NullPointerExceptions.


Optional optional = Optional.ofNullable("Hello");
optional.ifPresent(System.out::println);
      

Java 8 introduced several powerful features that made Java more modern and expressive. Stay tuned for more articles and tutorials on Java programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top