Java 8 POC - Proof of Concept
Key Features and Examples
1. Functional Interfaces:
Functional interfaces are interfaces with a single abstract method.
Example: java.util.function package.
Code Example:
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
MyFunctionalInterface example = () -> System.out.println("Hello, Java 8!");
2. Lambda Expressions:
Lambdas provide a clear and concise way to represent a method interface.
Code Example:
List<String> list = Arrays.asList("A", "B", "C");
list.forEach(item -> System.out.println(item));
3. Stream API:
Stream API is used to process collections of objects in a functional style.
Code Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
4. Optional Class:
Optional is a container object that may or may not contain a non-null value.
Code Example:
Optional<String> optional = Optional.ofNullable("Hello");
optional.ifPresent(System.out::println);
5. Method References:
Method references are a shorthand for lambda expressions.
Code Example:
List<String> names = Arrays.asList("John", "Jane", "Jake");
names.forEach(System.out::println);
6. Default Methods in Interfaces:
Java 8 allows default method implementations in interfaces.
Code Example:
interface MyInterface {
default void defaultMethod() {
System.out.println("Default Method in Interface");
}
7. Date and Time API:
Java 8 introduced a new date and time API in java.time package.
Code Example:
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
8. Nashorn JavaScript Engine:
Allows running JavaScript code directly from Java.
Code Example:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from Nashorn');");