Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

overloading - Why overload the varargs method of() in Java Stream interface?

The Stream interface has two overloads for the method of(). One of these is a variable-arity method while the other takes a single argument.

Is the single-argument method a performance optimization versus passing one argument to the variable-arity method? If so, how does it improve performance? The same questions could be asked of the empty() method, which would seem to be syntax sugar around the variable-arity of().

I see that the implementation differs between these methods, with the difference apparently being how the Spliterator is instantiated; but what advantage does this offer to the Stream API?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Empty stream and single element stream are very common use-cases, especially when you utilize the .flatMap(). For example, here's how Optional.stream() is implemented in Java-9:

public Stream<T> stream() {
    if (!isPresent()) {
        return Stream.empty();
    } else {
        return Stream.of(value);
    }
}

So given the stream of Optionals you can unwrap them into the flat stream this way:

streamOfOptionals.flatMap(Optional::stream);

Here you create tons of empty streams as well as single element streams, so optimizing such cases looks very reasonable. In particular, Stream.empty() unlike Stream.of() does not create an empty array and does not create the spliterator (it reuses the same spliterator instance). Stream.of(T) is also particularly optimized inside the StreamBuilderImpl, so no array is allocated for single element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...