According to Effective Java 2nd Ed, when you want to write a method signature that allows for varargs but still enforces that you have one element minimum at compile-time you should write the method signature this way:
public void something(String required, String ... additional) {
//... do what you want to do
}
If I want to stream all these elements, I've been doing something like this:
public void something(String required, String ... additional) {
Stream<String> allParams =
Stream.concat(Stream.of(required), Stream.of(additional));
//... do what you want to do
}
This feels really inelegant and wasteful, especially because I'm creating a stream of 1 and concatenating it with another. Is there a cleaner way to do this?
Stream.concat
seems fine to me...it's short, concise, it doesn't create copies of the data. You're creating a few extra wrapper objects, that's all. IMO really nothing wrong with it. Programming in Java, you just have to create small objects for things here and there.Stream.concat
is already miles ahead of merging them with anArrayList
or something like that.Spliterator<T>
and use it withStreamSupport.stream(spliterator, parallel)
but i really dont feel like that makes it any more readable or efficient.