NPE killer in Java8 to prevent NullPointerExceptions

In JDK8 the Optional<T> type monad has been introduced. The purpose of this class is essentially to facilitate the active thinking about the case when null might be assigned to an object causing a NullPointerException when this object will be dereferenced.

Consider this:
public static Optional<Drink> find(String name, List<Drink> drinks) {  
  for(Drink drink : drinks) {
    if(drink.getName().equals(name)) {
    return Optional.of(drink);
  return Optional.empty();
List<Drink> drinks = Arrays.asList(new Drink("Beer"), new Drink("Wine"), new Drink("Cocktail"));
Optional<Drink> found = find("Beer", drinks);
if(found.isPresent()) {
  Drink drink = found.get();
  String name = drink.getName();


Popular posts from this blog

Tuning ext4 for performance with emphasis on SSD usage

How to fix: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu