Java 8 cheatsheet

Functional interfaces

  • static: behaves like final methods
  • default: are similar to abstract methods: “default behaviour, but it can be overriden”
1
2
3
4
5
6
7
8
public interface Vehicle{
static String producer() {
return "N&F Vehicles";
}
default String getOverview() {
return "ATV made by " + producer();
}
}

Stream API

  • Reference to static methods
1
2
3
4
// with lambdas
boolean isReal = list.stream().anyMatch(u -> User.isRealUser(u));
// avoiding lambdas
boolean isReal = list.stream().anyMatch(User::isRealUser);
  • Reference to an instance method
1
long count = list.stream().filter(String::isEmpty).count();
  • Reference to a constructor
1
Stream<User> stream = list.stream().map(User::new);

Optional as nullpointer protection

  • Definition

    1
    Optional<String> optional = Optional.of("value");
  • Simplifying conditionals

    1
    2
    3
    4
    5
    // conditional
    List<String> listOpt = list != null ? list : new ArrayList<>();
    // optional
    List<String> listOpt = getList().orElse(new ArrayList<>());
    List<String> listOpt = getList().orElseGet(ArrayList::new);
  • Handling nullables with default values

    1
    2
    3
    4
    5
    Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
    String result = optionalUser
    .flatMap(OptionalUser::getAddress)
    .flatMap(OptionalAddress::getStreet)
    .orElse("not specified");
  • Handling nullable exceptions

    1
    2
    3
    String value = null;
    Optional<String> valueOpt = Optional.ofNullable(value);
    String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();