Naming java methods that return streams

api-design, java, java-8, java-stream

Solution

Since I wrote that paragraph I feel compelled to answer. :-)

Suppose you have a class that represents an aggregation of things of a single type, and you want to return a `Stream` of them to the caller.

If it's totally unambiguous as to what you're returning, you might just as well call the method `stream()`. There are a lot of methods in the JDK named `stream()` that return a stream of the obvious type.

Sometimes what you're returning is different representations of the same thing, or different kinds of things, or whatever. In that case there does seem to be a convention to choose a plural noun that represents the type of things being returned in the stream.

To see these, look in the Javadoc and click the Use link in the top navigation bar. This will take you to a cross-reference page. Look for all methods that have return values of the type you're interested in.

For example, see the Use pages for `Stream`, `IntStream`, `LongStream`, and `DoubleStream`. There are lots of methods named `stream()` that return streams. But there are also:

- `java.io.BufferedReader.lines()`

- `java.lang.CharSequence.chars()`

- `java.lang.CharSequence.codePoints()`

- `java.nio.CharBuffer.chars()`

- `java.nio.file.File.lines()`

- `java.util.Random.ints()`

- `java.util.Random.longs()`

- `java.util.Random.doubles()`

- `java.util.SplittableRandom.ints()`

- `java.util.SplittableRandom.longs()`

- `java.util.SplittableRandom.doubles()`

- `java.util.concurrent.ThreadLocalRandom.ints()`

- `java.util.concurrent.ThreadLocalRandom.longs()`

- `java.util.concurrent.ThreadLocalRandom.doubles()`

Of course, there are a lot of methods that don't conform to this. The NIO file utility class has `Files.find()`, `Files.list()`, and `Files.walk()`. A stream of results from splitting a string is returned by `java.util.regex.Pattern.splitAsStream`. I don't think anybody likes the `AsStream` suffix but then again, nobody could think of anything better. On the other hand, a proposed JDK 9 enhancement to get a stream of regex match results will be named `Matcher.results()`.

Problem

Is there naming convention for methods that return Stream? The only mention I found is this answer on S.O (last paragraph), but I don't see what is it based on.

Original source

Related problems