Search code examples
javajava-streamconcatenationoption-typevariadic-functions

How can I make stream with fixed arguments along with varargs?


Let's say we have the following method.

void some(int id, int... otherIds) {

}

How can I create a single IntStream with those two arguments?

IntStream.concat(
        IntStream.of(id),
        Optional.ofNullable(otherIds)
                .map(IntStream::of)
                .orElseGet(IntStream::empty)
);

It seems verbose. Do we have any concise idiom for that?


Solution

  • When you need to deal with nullable stream-source, you might use Stream.ofNullable() accessible with Java 9, which produces either a singleton-stream or an empty stream. It'll be cleaner than utilizing Optional.ofNullable() for the purpose of chaining methods on it.

    IntStream.concat(IntStream.of(id),
        Stream.ofNullable(otherIds).flatMapToInt(IntStream::of))
    

    Another option is to make use of Java 9 static method Objects.requireNonNullElse() which expects a nullable argument and a default value:

    IntStream.concat(IntStream.of(id),
        IntStream.of(Objects.requireNonNullElse(otherIds, new int[0])))
    

    And the simplest and cleanest solution will be a fail-fast implementation, that will throw a NullPointerException in case if array otherIds is null.

    IntStream.concat(IntStream.of(id), Arrays.stream(otherIds))
    

    A null-safe flavor of it (credits to @Holger):

    IntStream.concat(IntStream.of(id),
                     otherIds != null ? Arrays.stream(otherIds) : IntStream.empty())