Java 8

About

Java 8 introduced numerous significant features that changed the way Java developers write code.

1. Lambda Expressions

Lambda expressions provide a clear and concise way to represent anonymous functions. They eliminate the need for boilerplate code when implementing functional interfaces.

Example:

import java.util.*;

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Mary", "Peter", "Alice");

        // Using lambda expression to sort the list
        names.sort((s1, s2) -> s1.compareToIgnoreCase(s2));

        System.out.println(names);
    }
}

2. Functional Interfaces and @FunctionalInterface Annotation

A functional interface is an interface with exactly one abstract method, used as a type for lambda expressions.

Example:

3. Default and Static Methods in Interfaces

Interfaces can now contain default and static methods with implementations.

Example:

4. Streams API

The Streams API allows functional-style operations on collections.

Example:

5. Method References

Method references provide a shorthand notation for calling methods.

Example:

6. Optional Class

The Optional class helps avoid NullPointerException by wrapping values that may be null.

Example:

7. New Date and Time API (java.time package)

Java 8 introduced a modern java.time API to replace the legacy java.util.Date and java.util.Calendar.

Example:

8. Collectors in Streams

Collectors are used to accumulate elements of a stream into a collection.

Example:

9. forEach() Method in Iterable

Java 8 introduced the forEach method for Iterable to iterate through collections.

Example:

10. computeIfAbsent() and computeIfPresent() in Map

Java 8 enhanced the Map interface with new methods.

Example:

map.computeIfAbsent("B", key -> 10);

  • Checks if the key "B" exists in the map.

  • If not present, it computes a value using the lambda function key -> 10 and puts "B" with the computed value 10 into the map.

  • If already present, it does nothing and keeps the existing value.

map.computeIfPresent("A", (key, val) -> val * 2);

  • Checks if the key "A" exists in the map.

  • If present, it applies the function (key, val) -> val * 2, which doubles the value of "A".

  • If not present, it does nothing.

11. String Joiner (java.util.StringJoiner)

The StringJoiner class is used for efficient string concatenation.

Example:

12. Base64 Encoding and Decoding

Java 8 introduced Base64 encoding and decoding.

Example:

13. Arrays.parallelSort()

Java 8 introduced parallelSort() to sort arrays in parallel.

Example:

Last updated