Java 8 Features
1. Lambda Expressions
Syntax: (parameter1, parameter2) -> { // body }
Example:
List<String> names = Arrays.asList("A", "B", "C");
names.forEach(name -> System.out.println(name));
Use Cases:
Replacing anonymous classes (e.g., event listeners, Runnable)
Collections (e.g., forEach, filter, map)
Functional interfaces
2. Functional Interfaces
Definition:
An interface with exactly one abstract method
Annotated with @FunctionalInterface (optional but recommended)
Example:
@FunctionalInterface
interface MyFunc {
void print();
}
Common Functional Interfaces (from java.util.function):
| Interface | Method | Description |
| --------------- | ------------- | -------------------- |
| `Predicate<T>` | `test(T t)` | Returns boolean |
| `Function<T,R>` | `apply(T t)` | Transforms T into R |
| `Consumer<T>` | `accept(T t)` | Performs action on T |
| `Supplier<T>` | `get()` | Supplies value of T |
3. Stream API
Purpose:
Process data in a functional style (like SQL for collections).
Example:
List<String> result = list.stream()
.filter(s -> s.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
Types:
Intermediate: map, filter, sorted
Terminal: collect, forEach, count, reduce
Parallel Stream:
list.parallelStream().forEach(System.out::println);
4. Default and Static Methods in Interfaces
Default Method:
interface Vehicle {
default void start() {
System.out.println("Starting...");
}
}
Static Method:
interface Utility {
static int square(int x) {
return x * x;
}
}
5. Method References
ClassName::methodName
Types:
Static method: Class::staticMethod
Instance method: obj::instanceMethod
Constructor: Class::new
Example:
list.forEach(System.out::println);
6. Optional Class
Purpose:
Avoid NullPointerException.
Example:
Optional<String> name = Optional.of("Java");
name.ifPresent(System.out::println);
Methods:
of(value) – non-null only
ofNullable(value)
isPresent()
ifPresent(Consumer)
orElse(value)
orElseGet(Supplier)
orElseThrow()
7. Date and Time API (java.time.*)
Replaces: java.util.Date, Calendar
Key Classes:
| Class | Description |
| -------------------- | ------------------------------ |
| `LocalDate` | Date only (no time) |
| `LocalTime` | Time only (no date) |
| `LocalDateTime` | Date + time |
| `ZonedDateTime` | Date + time + timezone |
| `Period`, `Duration` | Difference between dates/times |
Example:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1995, Month.JULY, 20);
Period age = Period.between(birthday, today);
8. Nashorn JavaScript Engine
Java 8 introduced Nashorn, a JavaScript engine integrated into the JVM.
Allows execution of JavaScript code inside Java.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from JS');");
9. Collectors (java.util.stream.Collectors)
Used to collect stream elements into collections or strings.
Examples:
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(String::length, Function.identity()));
10. Repeatable Annotations
Allows multiple annotations of the same type on a single element.
Example:
@Hint("hint1")
@Hint("hint2")
public class Person {}
@Repeatable(Hints.class)
@interface Hint {
String value();
}
@interface Hints {
Hint[] value();
}
11. CompletableFuture & Concurrency Enhancements
Introduced CompletableFuture<T> for asynchronous programming.
Better than Future, with non-blocking chaining.
Example:
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
Summary Table
| Feature | Description |
| --------------------- | ----------------------------------------- |
| Lambda Expressions | Inline anonymous functions |
| Functional Interfaces | Interface with single abstract method |
| Stream API | Functional-style data processing |
| Optional | Avoid `null` and `NPE` |
| New Date-Time API | Modern date/time handling |
| Method References | Shorter lambda for existing methods |
| Default Methods | Allow method implementation in interfaces |
| CompletableFuture | Async task management |
| Collectors | Advanced stream collection utilities |
| Nashorn JS Engine | Run JavaScript in JVM |