Java 8 cheatsheet
Functional interfaces
- static: behaves like final methods
- default: are similar to abstract methods: “default behaviour, but it can be overriden”
1 | public interface Vehicle{ |
Stream API
- Reference to static methods
1 | // with lambdas |
- 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
5Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
String result = optionalUser
.flatMap(OptionalUser::getAddress)
.flatMap(OptionalAddress::getStreet)
.orElse("not specified");Handling nullable exceptions
1
2
3String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();