Top Five Reasons to Try Java 8

by
Tags: , , ,

Java 8 is a substantial improvement over Java 7. Here are my top five favorite features.

5. Optional

Programmers familiar with Guava will recognize this one. Is the return value or parameter optional? This explicitly states that in favor of returning or passing in a null. For example, if findById(String id) may not always find a value, return Optional instead of MyClass. Using Optional allows a cleaner API. No more guessing if null is a possibility. Now the caller can use isPresent(), orElse(defaultValue), or many other helper methods.

4. Date/Time

Everyone doing date/time calculations in Java 7 and earlier is hopefully using Joda-Time. The next generation is built into Java 8. Thread safe formatting, Immutable Date/Time classes, easier calculations, and much more.

For example, to find the age from January 1st, 1990 until today:

import java.time.*;
public class Birthday {
  public static final void main(String... args) {
    LocalDate today = LocalDate.now();
    LocalDate birthday = LocalDate.of(1990, 1, 31);
    Period age = Period.between(birthday, today);
    System.out.println("Age: " + age.getYears());
  }
}

3. Deferred Execution

Now that Functions can be passed into (and returned) from methods, log.isLogLevelEnabled and similar methods no longer needs to be spattered across the code base. Here is an example using java.util.function.Supplier from java.util.logging:

import java.util.logging.Logger;
 public class Hello {
   public static final void main(String... args) {
     // The String concatenation does not occur
     // unless info logging is enabled.
     Logger.getLogger(“hello”).info(()->”Hello “ + args[0]);
   }
 }
 

2. Mixins

Mixins arrive for Java with default methods in interfaces. If there is a conflict, the method is abstract and must be overridden in the implementing class. Here is an example (without a name conflict):

public interface Hello {
   default String hello(String name) {
     return "Hello " + name;
   }
 }
 public interface Print {
   default void print(String out) {
     System.out.println(out);
   }
 }
 public class PrintHello implements Print, Hello {
   public static final void main(String... args) {
     new PrintHello().apply(args[0]);
   }
   public void apply(String name) {
     print(hello(name));
   }
 }
 

1. Lambdas

Many pieces of code can be made clearer with lambdas. Here is a simple example that prints [A, B] by filtering uppercase letters and storing them in a Set.

import java.util.*;
 import java.util.stream.Collectors;
 public class Simple {
   public static final void main(String... args) {
     final List someLetters = Arrays
         .asList('A', 'B', 'a', 'b', 'z', 'A');
     System.out.println(someLetters
         .stream()
         .filter(Character::isUpperCase)
         .collect(Collectors.toSet()));
   }
 }
 

Lambda processing is lazy, the following only accesses the first two elements of the List.

import java.util.*;
 public class Lazy {
   public static final void main(String... args) {
     final List someLetters = Arrays
         .asList('A', 'B', 'a', 'B', 'z', 'A');
     System.out.println(someLetters
         .stream()
         .filter(letter -> letter == 'B')
         .findFirst()
         .get());
   }
 }
 

This is just a small sampling of the new features in Java 8. I hope it whetted your appetite for more.