Java 8 introduced several powerful features to improve code efficiency, conciseness, and performance.
1. Lambda Expressions (→)
Introduced functional-style programming in Java by allowing methods to be treated as first-class citizens
Benefits: Less code, more readability, and better performance.
2. Functional Interfaces
A functional interface has exactly one abstract method and can use lambda expressions.
3. Streams API (Functional-Style Operations on Collections)
Allows processing large collections of data in a more readable and parallelized way.
Key Methods in Streams API:
✔
filter(Predicate<T>)
→ Filters
elements based on a condition.
✔ map(Function<T,
R>)
→ Transforms each element.
✔ sorted()
→ Sorts the elements.
✔ collect(Collectors.toList())
→ Collects results into a List.
✔ forEach(Consumer<T>)
→ Iterates over elements.
4. Default and Static Methods in Interfaces
Allows adding methods to interfaces without breaking existing implementations.
5. Optional (Avoid NullPointerException)
Optional<T>
is used to
handle null values safely and avoid
NullPointerException.
6. Method References (::)
A concise way to refer to methods of an existing class instead of writing a lambda expression.
Types of Method References:
✔
ClassName::staticMethod
(e.g.,
Math::max
)
✔ object::instanceMethod
(e.g., System.out::println
)
✔
ClassName::instanceMethod
(e.g.,
String::toUpperCase
)
7. New Date and Time API (java.time
Package)
A modern API replacing the legacy java.util.Date
and Calendar
.
Key Classes:
✔
LocalDate
→ Only date (YYYY-MM-DD).
✔
LocalTime
→ Only time (HH:MM:SS).
✔
LocalDateTime
→ Both date and time.
✔
DateTimeFormatter
→ Custom date
formatting.