Jishnu Prathap
Jishnu Prathap

Reputation: 2033

What is NullSafe way to concatenate two Streams?

I have two streams of integers guestsTravelWith and guests, which I am concatenating but throwing error when any one of stream is Null. Is there a nullsafe way to concatenate two streams? Or using if conditions is my only hope?

Stream<Integer> guests = code+some_method();
Stream<Integer> guestsTravelWith = code+some_method();
Stream.concat(guestsTravelWith, guests)

Upvotes: 3

Views: 1705

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19555

Why not just to filter out null streams?

Stream<Integer> s1 = null;
Stream<Integer> s2 = Stream.of(1, 2, null, 4);
    
Stream.of(s1, s2)
      .filter(Objects::nonNull) // Stream<Stream>
      .flatMap(s -> s) // or Function.identity()
      .forEach(System.out::println);

Update by Holger's comment
Stream.concat should be replaced with Stream.of and null-safe Stream::flatMap:

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)

    Stream<Integer> s1 = null;
    Stream<Integer> s2 = Stream.of(1, 2, null, 4);

    Stream.of(s1, s2)
          .flatMap(s -> s) // or Function.identity()
          .forEach(System.out::println);

Output:

1
2
null
4

Upvotes: 6

Eugene
Eugene

Reputation: 120858

Not nice at all, but:

Stream.ofNullable(guestsTravelWith).orElse(Stream.empty()).flatMap(Function.identity())

Or you know, the "less funner" way:

guests == null ? Stream.empty() : guests;

You should reconsider the methods that return null Stream to begin with, which is a terrible idea.

Upvotes: 9

Gatusko
Gatusko

Reputation: 2598

If you are using Java 9 use Strem.ofNullable

Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.

Upvotes: 1

Related Questions