π Java 8 Features (Must-Know)¶
Java 8 didnβt just add features, it quietly rewired how Java thinks π§ βοΈ From verbose boilerplate to sleek, functional styleβ¦ itβs like switching from a typewriter to a smart IDE.
Letβs break it down in a way you can use in interviews and code immediately.
πΉ 1. Lambda Expressions¶
π Write functions like mini one-liners instead of bulky anonymous classes
List<String> list = Arrays.asList("A", "B", "C");
// Before Java 8
for (String s : list) {
System.out.println(s);
}
// Java 8
list.forEach(s -> System.out.println(s));
π― Use Case¶
- Functional programming
- Cleaner, concise code
πΉ 2. Functional Interfaces¶
π Interface with only one abstract method
Examples:
- Runnable
- Comparator
πΉ 3. Stream API¶
π Process collections like a pipeline π οΈ
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.forEach(System.out::println);
π― Key Operations¶
filter()β selectmap()β transformcollect()β gather
πΉ 4. Default Methods (Interface Enhancement)¶
π Interfaces can now have method implementations
πΉ 5. Method References¶
π Shortcut for lambda expressions
Instead of:
πΉ 6. Optional Class¶
π Avoid NullPointerException
π― Key Methods¶
isPresent()orElse()orElseGet()
πΉ 7. Date & Time API (java.time)¶
π Modern replacement for old Date
LocalDate today = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dt = LocalDateTime.now();
π― Benefits¶
- Immutable
- Thread-safe
πΉ 8. Collectors¶
π Used with streams
πΉ 9. Parallel Streams¶
π Easy multithreading
β οΈ Use carefully (not always faster)
πΉ 10. Nashorn JavaScript Engine¶
π Run JavaScript inside Java (rarely used now)
π― Interview Answer (Perfect Summary)¶
βJava 8 introduced major features like lambda expressions, functional interfaces, Stream API, Optional class, default methods, method references, and a new Date-Time API. These features enable functional programming, improve readability, and reduce boilerplate code.β
π§ Real-World Impact¶
Before Java 8:
After Java 8:
β οΈ Common Interview Traps¶
- Stream is not a data structure
- Optional should not be used for fields
- Parallel stream is not always faster
π Memory Trick¶
Think Java 8 = FLOOD
- Functional interfaces
- Lambda
- Optional
- Operations (Streams)
- Date-Time API