1

I have the following code in my example:

final List<Optional<String>> messages = 
    ImmutableList.of(Optional.empty(), Optional.empty() );

final String dummy = messages.stream()
        .filter( Optional::isPresent )
        .map( message -> message.get() )
        .collect( Collectors.joining( "\n---\n" ) );

Now on debugging, the value of the variable dummy is always an empty string. Is that a result of the stream, or the behavior of the Collectors.joining method?

I was under the assumption that the resultant String would be null.

7
  • what are you expecting with empty Optional ?
    – Ryuzaki L
    Commented Feb 19, 2021 at 18:21
  • I'm expecting a null string as mentioned? Commented Feb 19, 2021 at 18:21
  • That behaviour is purely dependent on the collector you used. Collectors.joining() doesn't explicitly document how it handles empty inputs, but I'm not suprised by an empty string. Indeed I wouldn't expect null to be returned by this ever. Commented Feb 19, 2021 at 18:21
  • I tried looking for the javadocs for the joining method and found none. I might have to look in the source code. Commented Feb 19, 2021 at 18:22
  • It's the collector
    – Michael
    Commented Feb 19, 2021 at 18:23

0

Browse other questions tagged or ask your own question.