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

  1. Lambda Expressions
  2. Functional Interfaces
  3. Stream API
  4. Optional Class
  5. New Date and Time API
  6. Default and Static Methods in Interfaces
  7. Method References

  1. 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

(parameters) -> expression

or

(parameters) -> { statements; }

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 r1 is created using an anonymous class.
  • Runnable r2 is created using a lambda expression, which is more concise.

  1. 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

@FunctionalInterface
interface MyFunctionalInterface {
    void myMethod();
}

Explanation

  • MyFunctionalInterface is a functional interface with a single abstract method myMethod.

  1. 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

  • filter filters the elements starting with "c".
  • map converts each string to uppercase.
  • sorted sorts the elements.
  • forEach prints each element.

  1. 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.of creates an Optional containing the string "Hello".
  • ifPresent checks if a value is present and prints it.

  1. 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, and LocalDateTime are used to represent date, time, and both date and time respectively.

  1. 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

  • defaultMethod is a default method in the interface.
  • staticMethod is a static method in the interface.

  1. 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

List<String> list = Arrays.asList("a", "b", "c");

list.forEach(System.out::println);

Explanation

  • System.out::println is a method reference to the println method of System.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, 6

Exercise 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

Module 2: Control Flow

Module 3: Object-Oriented Programming

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

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved