Java 8 Features - Proof of Concept (POC)
Introduction
Java 8 is one of the most important versions of Java. It introduced many new features that make
coding easier, cleaner, and more efficient. The main goal of Java 8 is to support functional
programming and reduce the amount of code developers need to write.
Features Covered
1. Lambda Expressions
Lambda Expressions provide a shorter way to write anonymous functions.
Example:
List<String> names = [Link]("Ram", "John", "David");
[Link](name -> [Link](name));
Benefit:
- Less code
- Better readability
- Easy to pass behavior as a parameter
2. Functional Interface
A Functional Interface contains only one abstract method.
Example:
@FunctionalInterface
interface Greeting{
void sayHello();
}
3. Method Reference
Method References are a shorter form of Lambda Expressions.
Example:
[Link]([Link]::println);
4. Stream API
Stream API is used to process collections of data in a simple and efficient way.
Example:
List<Integer> numbers = [Link](2,4,6,8);
[Link]()
.filter(n -> n>4)
.forEach([Link]::println);
5. Optional Class
Optional helps avoid NullPointerException.
Example:
Optional<String> name = [Link]("Rajeshwari");
[Link]([Link]());
6. Default Methods
Interfaces can contain default methods with implementation.
Example:
interface Vehicle{
default void start(){
[Link]("Vehicle Started");
}
}
7. Static Methods in Interface
Interfaces can also contain static methods.
Example:
interface Demo{
static void display(){
[Link]("Java 8");
}
}
8. Date and Time API
Java 8 introduced a new Date and Time API.
Example:
LocalDate today = [Link]();
[Link](today);
9. forEach() Method
Used to iterate over collections.
Example:
[Link]([Link]::println);
10. Collectors
Collectors are used to collect Stream results into a List, Set, or Map.
Example:
List<String> result = [Link]()
.filter(name -> [Link]("R"))
.collect([Link]());
11. Built-in Functional Interfaces
Java 8 provides predefined functional interfaces.
Predicate → Checks a condition
Function → Takes input and returns output
Consumer → Accepts input without returning anything
Supplier → Supplies data without taking input
Example:
Predicate<Integer> check = n -> n > 18;
[Link]([Link](20));