top of page
Search

Java 8 New Feature

  • Writer: Rajkishore R
    Rajkishore R
  • Feb 23
  • 3 min read



1. Lambda Expressions (Functional Interfaces)

Lambda expressions provide a concise way to represent anonymous functions, making code more readable and reducing boilerplate.

Example:

java

import java.util.*;


public class LambdaExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");


// Using Lambda Expression

names.forEach(name -> System.out.println(name));

}

}


Explanation:

  • The forEach method takes a lambda expression (name -> System.out.println(name)) to print each name.

  • No need to write explicit for-loops or anonymous classes.


2. Functional Interfaces (java.util.function package)

A functional interface is an interface with only one abstract method, used in lambda expressions.

Example:

import java.util.function.*;


public class FunctionalInterfaceExample {

public static void main(String[] args) {

// Using Function interface to square a number

Function<Integer, Integer> square = x -> x * x;

System.out.println("Square of 5: " + square.apply(5));

}

}

Explanation:

  • Function<T, R> takes an input (T) and returns a result (R).

  • The lambda expression x -> x * x replaces the need for defining a separate method.

Common functional interfaces:

  • Predicate<T> – returns boolean (e.g., x -> x > 10)

  • Consumer<T> – takes an input but returns nothing (e.g., x -> System.out.println(x))

  • Supplier<T> – provides a value (e.g., () -> "Hello")

  • Function<T, R> – transforms an input (e.g., x -> x * 2)


3. Stream API (java.util.stream package)

Streams allow functional-style operations on collections, such as filtering, mapping, and reducing.

Example:

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class StreamExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");


// Filter names starting with 'A' and collect them into a list

List<String> filteredNames = names.stream()

.filter(name -> name.startsWith("A"))

.collect(Collectors.toList());


System.out.println(filteredNames);

}

}


import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class StreamExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");


// Filter names starting with 'A' and collect them into a list

List<String> filteredNames = names.stream()

.filter(name -> name.startsWith("A"))

.collect(Collectors.toList());


System.out.println(filteredNames);

}

}


Explanation:

  • .stream() converts the list into a stream.

  • .filter(name -> name.startsWith("A")) filters only names starting with "A".

  • .collect(Collectors.toList()) converts the stream back to a list.


4. Default Methods in Interfaces

Interfaces can now have default methods, allowing method implementation inside an interface.

Example:

interface Vehicle {

default void honk() {

System.out.println("Honking...");

}

}


class Car implements Vehicle {}


public class DefaultMethodExample {

public static void main(String[] args) {

Car car = new Car();

car.honk(); // Output: Honking...

}

}


Explanation:

  • The interface Vehicle provides a default implementation of honk().

  • The class Car implements Vehicle but does not need to override honk().


5. Optional Class (java.util.Optional)

Avoids NullPointerException by providing a container that may or may not contain a value.

Example:

import java.util.Optional;


public class OptionalExample {

public static void main(String[] args) {

Optional<String> optionalValue = Optional.ofNullable(null);


// Use ifPresent to execute code only if a value is present

optionalValue.ifPresent(value -> System.out.println("Value: " + value));


// Use orElse to provide a default value

System.out.println(optionalValue.orElse("Default Value"));

}

}


Explanation:

  • Optional.ofNullable(null) creates an empty optional.

  • ifPresent() executes only if a value exists.

  • orElse() provides a default if no value is present.


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

A modern replacement for the old java.util.Date.

Example:

import java.time.LocalDate;

import java.time.LocalTime;

import java.time.LocalDateTime;


public class DateTimeExample {

public static void main(String[] args) {

LocalDate today = LocalDate.now();

LocalTime now = LocalTime.now();

LocalDateTime dateTime = LocalDateTime.now();


System.out.println("Date: " + today);

System.out.println("Time: " + now);

System.out.println("Date & Time: " + dateTime);

}

}


Explanation:


7. Method References

A shorthand for lambda expressions.

Example:

import java.util.Arrays;

import java.util.List;


public class MethodReferenceExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");


// Using method reference instead of lambda expression

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

}

}


Explanation:

  • Instead of writing name -> System.out.println(name), we use System.out::println.


8. Collectors in Stream API (Collectors.joining())

The Collectors class provides utility methods for reducing stream elements.

Example:

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class CollectorsExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");


// Join names with a comma

String result = names.stream()

.collect(Collectors.joining(", "));


System.out.println(result); // Output: Alice, Bob, Charlie

}

}


Explanation:

  • Collectors.joining(", ") joins the list elements into a single String.


Conclusion

Java 8 introduced many powerful features, including:

  • Lambda Expressions for concise code.

  • Functional Interfaces for higher-order functions.

  • Stream API for processing collections efficiently.

  • Default Methods in interfaces.

  • Optional to avoid NullPointerException.

  • New Date-Time API for modern date handling.

  • Method References for clean and readable code.

  • Collectors for efficient data manipulation.

 
 
 

Comments


bottom of page