Optional
-
void ifPresentOrElse(Consumer action, Runnable emptyAction)
Applies an action if the element is present or the runnable otherwise ex:
Optional option = Optional.of(1); option.ifPresentOrElse(System.out::println,()->System.out.println("not found"));
-
Optional or(Supplier supplier)
Returns the option value of the supplier if the host option is absent. Say we want to try to compute some value from different methods and we stop when we succeed.
Optional fromX(){ .. } Optional fromY(){ .. } fromX().or(()-> fromY());
-
Stream stream()
converts an Option to a Stream, very useful when combined with streams. Say you have a list on optionals and you want to filter out the empty ones and leave the non empty ones, simply you can convert to a Stream and flatmap it.
Stream<Integer> nonEmpty = Stream.of(fromX(), fromY(), fromZ()).flatMap(Optional::stream)
java.util.Objects
-
T requireNonNullElse(T obj, T defaultObj)
Returns the first argument if it’s not null or the defaultObj otherwise, throws an NPE if defaultObj is null.
-
T requireNonNullElseGet(T obj, Supplier supplier)
Similar to the one before but this one takes supplier rather than a value and hence.
-
int checkIndex(int index, int length)
throws an IndexOutOfBoundsException if index= length or length
-
int checkFromToIndex(int fromIndex, int toIndex, int length)
throws an IndexOutOfBoundsException if fromIndex toIndex or toIndex>length or length
-
int checkFromIndexSize(int fromIndex, int size, int length)
throws an IndexOutOfBoundsException if fromIndex length or length
Map
-
Map of()
Returns an empty immutable Map
Map<String,Integer> empty = Map.of();
-
Map of(K k1, V v1, ...., K k10, V v10)
Returns an immutable Map that contains the provided key-value pairs
Map<String,Integer> empty = Map.of("hi", 1, "there", 2);