Obtaining a Stream: why and where?

The Java Stream API introduces a new methodology for iterating through collections and other data sources. This allows us to use the succinct syntax and other advantages of streams and lambdas when performing operations such as iterating over a list or array, traversing a directory structure or reading lines from a file. By using the new Stream-based methods, we gain a number of advantages over previous means of iteration. Coupled with lambdas, the advantages of the Stream API include:

Therefore, in various cases where we previously had to iterate through arrays and collections or write iteration code ourselves, it would be nice to be able to use the Stream API instead. To assist with this, various JDK methods that return arrays, collections or Iterators have been complemented with equivalents that return a Stream. The following table gives a summary of some of the common Stream equivalents to existing Java API calls introduced from Java 8 onwards:

Old methodStream equivalent
list.iterator()
set.iterator()
list.stream()
set.stream()
Arrays.asList(arr)
Arrays.asList(arr).iterator()
Arrays.stream(arr)
Arrays.asList(arr)
Arrays.asList(obj1, obj2...).iterator()
Stream.of(obj1, obj2...)
Files.readAllLines(path)Files.lines(path)
bufferedReader.readLine()bufferedReader.stream()
pattern.split(seq)pattern.splitAsStream(seq)
string.toCharArray()string.chars()
charSequence.toString().toCharArray()charSequence.chars()
random.nextInt()
...
random.nextDouble()
...
random.ints()
random.doubles()
Files.list(path)Files.newDirectoryStream(path)
Files.walk(path)Files.walkFileTree(path)
Files.newDirectoryStream(path).iterator()Files.files(path)

Further reading

As an example of using the new Stream-based API calls, we can turn in more detail to the common case of streaming lines from a file.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.