Java 1.9 Diary


  • 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)


  • 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 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);

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: