Java 8 Features with Examples

Category : Java | Sub Category : Java 8 Features | By Prasad Bonam Last updated: 2023-07-09 09:33:49 Viewed : 331


Java 8 Features with Examples:

Here are some Java 8 features with examples:

  1. Lambda Expressions: Lambda expressions allow you to define anonymous functions concisely. They are commonly used with functional interfaces. Her is an example:
java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Using lambda expression with forEach method numbers.forEach((Integer number) -> System.out.println(number));
  1. Stream API: The Stream API provides a powerful way to perform operations on collections. It supports operations like filtering, mapping, reducing, and more. Here is an example:
java
List<String> fruits = Arrays.asList("apple", "banana", "cherry", "durian"); // Using stream to filter and map elements List<String> uppercaseFruits = fruits.stream() .filter(fruit -> fruit.length() > 5) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(uppercaseFruits); // Output: [BANANA, CHERRY]
  1. Functional Interfaces: Functional interfaces represent single abstract methods and can be used with lambda expressions. Here is an example:
java
// Functional interface with a single abstract method interface MathOperation { int operate(int a, int b); } // Using lambda expression with functional interface MathOperation addition = (a, b) -> a + b; System.out.println(addition.operate(5, 3)); // Output: 8
  1. Default Methods: Default methods allow adding methods with default implementations to interfaces. They facilitate backward compatibility when adding new methods to existing interfaces. Here is an example:
java
// Interface with a default method interface Shape { void draw(); default void display() { System.out.println("Displaying shape"); } } // Implementing interface with default method class Circle implements Shape { @Override public void draw() { System.out.println("Drawing circle"); } } // Using default method Circle circle = new Circle(); circle.draw(); // Output: Drawing circle circle.display(); // Output: Displaying shape
  1. Optional Class: The Optional class provides a way to handle potentially null values more explicitly. It helps prevent null pointer exceptions. Here is an example:
java
Optional<String> optionalName = Optional.ofNullable(null); // Using Optional to handle null value String name = optionalName.orElse("Unknown"); System.out.println(name); // Output: Unknown

These examples showcase some of the features introduced in Java 8. They demonstrate the usage of lambda expressions, stream operations, functional interfaces, default methods, and the Optional class. Java 8 offers a wealth of new capabilities that enhance the expressiveness and functionality of the language.


Search
Related Articles

Leave a Comment: