Java_8_Interview_Questions
Java_8_Interview_Questions
Lambda Expressions, Functional Interfaces, Stream API, Default Methods, Method References,
interfaces) concisely using an expression. It eliminates the need for anonymous class
implementations.
Example:
@FunctionalInterface
interface Greeting {
greet.greet("John");
A functional interface has only one abstract method, and it may contain multiple default or static
@FunctionalInterface
interface Converter {
System.out.println(converter.convert("123"));
The Stream API enables functional-style operations on streams of elements, such as collections. It
allows you to process elements in a sequence efficiently, providing operations like map, filter, and
reduce.
Example:
import java.util.*;
import java.util.stream.*;
.mapToInt(n -> n)
.sum();
System.out.println(sum);
Optional is used to represent values that may or may not be present, avoiding
NullPointerExceptions. It provides methods like isPresent, ifPresent, and orElse to handle null
values safely.
Example:
import java.util.Optional;
System.out.println(optional.orElse("Default Value"));
System.out.println(emptyOptional.orElse("Default Value"));
Java 8 introduced default methods that allow you to add method implementations directly in
interfaces. This is useful when you want to add new methods to an existing interface without
Example:
interface MyInterface {
obj.greet();
Example:
import java.util.*;
);
listOfLists.stream()
.forEach(System.out::println); // map
listOfLists.stream()
.forEach(System.out::println); // flatMap
Method references are a shorthand syntax for calling a method, often used in place of a lambda
Example:
import java.util.*;
Example:
import java.util.*;
The forEach method is a terminal operation that iterates over the elements of the stream and
Example:
import java.util.*;
numbers.stream().forEach(System.out::println);
}
11. What is the difference between anyMatch, allMatch, and noneMatch in Java 8 streams?
Example:
import java.util.*;
The collect method is a terminal operation that transforms the stream's elements into a different
Example:
import java.util.*;
import java.util.stream.*;
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
The peek method allows you to perform an action on each element of the stream without modifying
Example:
import java.util.*;
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
14. What is the Optional class, and how do you use it?
Optional is a container object that may or may not contain a non-null value. It provides methods like
isPresent(), ifPresent(), and orElse() to handle null values in a cleaner way.
Example:
import java.util.Optional;
Java 8 introduced the java.time package, which includes classes like LocalDate, LocalTime,
LocalDateTime, ZonedDateTime, and more to handle dates and times more efficiently.
Example:
import java.time.*;
System.out.println(today);