Java Optional.ofNullable(Object[] objects) with streams and boolean result

Viewed 461

I'm trying to implement a utility method like this

boolean allNotNull( LocalDate... objects )

so that it returned true only for the case when there are elements (objects vararg is not null) and there are no null elements inside it. Also I want to implement it in functional style using Streams and Optionals and not involving any if statements.

The solution seemed to be obvious:

private static boolean allNotNull( LocalDate... objects )
{

    boolean allNotNull = Optional.ofNullable( objects )
                                 .stream()
                                 .flatMap( Arrays::stream )
                                 .noneMatch( Objects::isNull );
    return allNotNull;
}

But it always returns true if objects vararg is null. The reason must be that Optional.stream() returns Stream.empty() for this case which always returns true despite the predicate:

    Assert.assertTrue( Stream.empty().noneMatch( o -> true ));   //always true
    Assert.assertTrue( Stream.empty().noneMatch( o -> false ));  //also always true

I feel very stupid, but my question would be: is there a way to implement a utility method like this using Optional.ofNullable() for input varargs (arrays/colections) using only streams and optionals and avoiding ifs?

Below is my main method with some tests:

public static void main( String[] args )
{
    Assert.assertFalse( allNotNull( null ) );

    Assert.assertFalse( allNotNull( LocalDate.now(), null, LocalDate.MIN ) );

    Assert.assertTrue( allNotNull( LocalDate.MIN ) );
    Assert.assertTrue( allNotNull( LocalDate.MIN, LocalDate.EPOCH, LocalDate.EPOCH ) );

    Assert.assertFalse( allNotNull() );
}

Thanks in advance!

1 Answers

I did not try the code, but it should work like this (if you insist using Optionals):

boolean allNotNull( LocalDate... objects ){
   return Optional.ofNullable(objects)
                  .map(Arrays::stream)
                  .map(s -> s.noneMatch(Objects::isNull))
                  .orElse(false);
}

Without Optionals you could write it as

boolean allNotNull( LocalDate... objects ){
   return objects != null && Arrays.stream(objects).noneMatch(Objects::isNull);
}
Related