'How can I make stream with fixed arguments along with varargs? [duplicate]
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 1:[1]
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())
Solution 2:[2]
Well, Alexander Ivanchenko has already mentioned three options.
Here's another one:
Objects.requireNonNull(otherIds);
Stream.of(new int[] { id }, otherIds)
.flatMapToInt(Arrays::stream)
I think otherIds
should not be null
, and should be considered a programmer error. With Objects::requireNonNull
it fails-fast.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | MC Emperor |