Naming java methods that return streams

*爱你&永不变心* 提交于 2019-12-05 05:13:14

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!