Stream
A stream is nothing, but a sequence of objects. It offers us various methods to produce the desired result in minimum lines of code. Stream takes inputs from Collections, Arrays or I/O channels and provides the result as per the pipelined methods, but don’t change the original data structure.
How to create Streams
There are multiple ways to create a stream instance of various sources.
Empty Stream
We create an empty Stream with the help of empty() method when we want to avoid returning null for Streams having no element.
For example:
Stream<String> emptyStream = Stream.empty();
Stream of Array
One of the sources is an Array to create a stream. We call it Stream of Array. Below are the two ways to create an Array of Streams.
For example:
String[] array = new String[]{"p", "q", "r"};
Stream<String> streamOfArray= Arrays.stream(array);
Stream<String> streamOfArray = Stream.of("p", "q", "r");
Stream of Collection
Needless to say, we can create stream of any type of Collection like Set, List.
For example:
Collection<String> collection = Arrays.asList("x", "y", "z");
Stream<String> streamOfCollection = collection.stream();
List<String> list = List.of("x", "y", "z"); Stream<String> streamOfList = list.stream();
Stream of Primitives
We can create streams of three primitive types such as int, long and double in Java 8. For that, we have three special interfaces : IntStream, LongStream, DoubleStream to work on int, long and double respectively.
We can use two methods to generate any of the three types of streams of primitives. These are : range(int startInclusive, int endExclusive) and rangeClosed(int startInclusive, int endInclusive)
range(int startInclusive, int endExclusive) method creates an ordered stream from the first parameter to the second parameter. It increments the value of subsequent elements with the step equal to 1. The result doesn’t include the last parameter, it is just an upper bound of the sequence.
rangeClosed(int startInclusive, int endInclusive) method does the same thing with only one difference, the second element is included.
For example :
IntStream intStream = IntStream.range(1, 4);
LongStream longStream = LongStream.rangeClosed(1, 4);
Since Java 8, the Random class provides a wide range of methods for generating streams of primitives.
For example, the following code creates a DoubleStream, which has four elements:
Random random = new Random(); DoubleStream doubleStream = random.doubles(4);
Stream of String
Even we can use String as a source for creating a stream with the help of the chars() method of the String class. Since there is no interface for CharStream in JDK, we use the IntStream to represent a stream of chars instead. For example:
IntStream streamOfChars = "pqr".chars();
Stream via Stream.generate()
In order to generate the elements, the generate() method accepts a Supplier<T>. As the resulting stream is infinite, we should define the desired size, or the generate() method will work until it reaches the memory limit.
For example, the code below will create a sequence of twenty strings with the value “pqr”.
Stream<String> generatedStream = Stream.generate(() -> "pqr").limit(20);
Stream via Stream.builder()
While using this method of creating streams, we should specify the desired type, otherwise the build() method will create an instance of Stream<Object> by default.
For example, the code below will create the Stream<String>.
Stream<String> streamBuilder = Stream.<String>builder().add("p").add("q").add("r").build();
Stream via Stream.iterate()
If you want to create an infinite stream, use iterate() method. For example, the code below will create a Stream of integers starting from value 24, as the first parameter of the method is 24. The second element in the stream will be 28, as per the expression in the second parameter of the method.
Stream<Integer> streamIterated = Stream.iterate(24, n -> n + 4).limit(20);
Stream of a File
When we create a stream of a file containing the text, every line of the text becomes an element of the stream. Furthermore, Java NIO class Files offers us to generate a Stream<String> of a text file through the lines() method.
For example:
Path path = Paths.get("D:\\myfile.txt");
Stream<String> streamOfStrings = Files.lines(path);
Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
Comments