Category : Java | Sub Category : Java 8 Features | By Prasad Bonam Last updated: 2023-07-09 15:03:49 Viewed : 67
Java 8 Features with Examples:
Here are some Java 8 features with examples:
javaList<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Using lambda expression with forEach method
numbers.forEach((Integer number) -> System.out.println(number));
javaList<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]
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
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
javaOptional<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.