Java 8 introduced several significant features that revolutionized the way Java programming is done. This module will cover the most important features introduced in Java 8, including Lambda Expressions, the Stream API, the new Date and Time API, and more.
Key Concepts
- Lambda Expressions
- Functional Interfaces
- Stream API
- Optional Class
- New Date and Time API
- Default and Static Methods in Interfaces
- Method References
- Lambda Expressions
Lambda expressions provide a clear and concise way to represent one method interface using an expression. They enable you to treat functionality as a method argument or treat a code as data.
Syntax
or
Example
// Traditional way of creating a Runnable
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!");
}
};
// Using Lambda Expression
Runnable r2 = () -> System.out.println("Hello World!");Explanation
Runnable r1is created using an anonymous class.Runnable r2is created using a lambda expression, which is more concise.
- Functional Interfaces
A functional interface is an interface that contains only one abstract method. They can have multiple default or static methods. The @FunctionalInterface annotation is used to ensure that the interface can't have more than one abstract method.
Example
Explanation
MyFunctionalInterfaceis a functional interface with a single abstract methodmyMethod.
- Stream API
The Stream API is used to process collections of objects. A stream is a sequence of elements supporting sequential and parallel aggregate operations.
Example
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);Explanation
filterfilters the elements starting with "c".mapconverts each string to uppercase.sortedsorts the elements.forEachprints each element.
- Optional Class
The Optional class is a container object which may or may not contain a non-null value. It is used to avoid NullPointerException.
Example
Optional<String> optional = Optional.of("Hello");
optional.ifPresent(System.out::println); // prints "Hello"Explanation
Optional.ofcreates an Optional containing the string "Hello".ifPresentchecks if a value is present and prints it.
- New Date and Time API
Java 8 introduced a new Date and Time API under the java.time package. It is more comprehensive and user-friendly than the previous java.util.Date and java.util.Calendar classes.
Example
LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.now(); System.out.println(date); // prints current date System.out.println(time); // prints current time System.out.println(dateTime); // prints current date and time
Explanation
LocalDate,LocalTime, andLocalDateTimeare used to represent date, time, and both date and time respectively.
- Default and Static Methods in Interfaces
Java 8 allows you to add non-abstract methods to interfaces using the default and static keywords.
Example
interface MyInterface {
default void defaultMethod() {
System.out.println("Default Method");
}
static void staticMethod() {
System.out.println("Static Method");
}
}
class MyClass implements MyInterface {}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.defaultMethod(); // prints "Default Method"
MyInterface.staticMethod(); // prints "Static Method"
}
}Explanation
defaultMethodis a default method in the interface.staticMethodis a static method in the interface.
- Method References
Method references provide a way to refer to methods without invoking them. They are used to refer to a method of an existing class or object.
Example
Explanation
System.out::printlnis a method reference to theprintlnmethod ofSystem.out.
Practical Exercises
Exercise 1: Using Lambda Expressions
Write a lambda expression to sort a list of strings in reverse order.
Solution
List<String> list = Arrays.asList("a", "b", "c");
list.sort((s1, s2) -> s2.compareTo(s1));
System.out.println(list); // prints [c, b, a]Exercise 2: Using Stream API
Filter a list of integers to find even numbers and print them.
Solution
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println); // prints 2, 4, 6Exercise 3: Using Optional
Create an Optional object and check if it contains a value.
Solution
Optional<String> optional = Optional.of("Hello");
if (optional.isPresent()) {
System.out.println(optional.get()); // prints "Hello"
}Conclusion
In this module, we covered the major features introduced in Java 8, including Lambda Expressions, the Stream API, the new Date and Time API, and more. These features have significantly improved the way Java code is written and have made it more concise and readable. Understanding and utilizing these features will help you write more efficient and modern Java code.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection
