In this tutorial, we will learn different ways to create Stream objects using different sources. First, we will see the overview of Stream and the characteristics of streams.
Learn Stream API at https://www.javaguides.net/p/java-8-stream-api-tutorial.html
Check out Stream API for beginners at https://www.javaguides.net/2020/04/java-8-stream-tutorial-for-beginners.html
Video Tutorial
This tutorial explained in below youtube video:
1. Stream API Overview
A stream represents a sequence of objects from a source, which supports aggregate operations.
Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces, and an enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package in your programs.
Learn more about Streams at https://www.javaguides.net/p/java-8-stream-api-tutorial.html
2. Characteristics of a Stream
- A stream provides a set of elements of a specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements.
- Source − Stream takes Collections, Arrays, or I/O resources as an input source.
- The stream is functional in nature. Operations performed on a stream does not modify its source.
- Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.
3. Different ways to create Stream objects in Java 8
1. Empty Stream
The empty() method should be used in case of the creation of an empty stream:
Stream<String> stream = Stream.empty();
stream.forEach(System.out::println);
It's often the case that the empty() method is used upon creation to avoid returning null for streams with no element:
public Stream<String> streamOf(List<String> list) {
return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}
2. From Collections
A stream can be created of any type of Collection (Collection, List, Set):
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
Collection<String> collection = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
Stream<String> stream2 = collection.stream();
stream2.forEach(System.out::println);
List<String> list = Arrays.asList("JAVA", "J2EE", "Spring", "Hibernate");
Stream<String> stream3 = list.stream();
stream3.forEach(System.out::println);
Set<String> set = new HashSet<>(list);
Stream<String> stream4 = set.stream();
stream4.forEach(System.out::println);
}
}
Output:
JAVA
J2EE
Spring
Hibernate
JAVA
J2EE
Spring
Hibernate
JAVA
Hibernate
J2EE
Spring
3. From Arrays
Array can be a source of a Stream or Array can be created from the existing array or of a part of an array:
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Stream;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
// Array can also be a source of a Stream
Stream<String> streamOfArray = Stream.of("a", "b", "c");
streamOfArray.forEach(System.out::println);
// creating from existing array or of a part of an array:
String[] arr = new String[] { "a", "b", "c" };
Stream<String> streamOfArrayFull = Arrays.stream(arr);
streamOfArrayFull.forEach(System.out::println);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
streamOfArrayPart.forEach(System.out::println);
}
}
Output:
a
b
c
a
b
c
b
c
4. From Stream.builder()
When a builder is used the desired type should be additionally specified in the right part of the statement, otherwise, the build() method will create an instance of the Stream:
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
streamBuilder.forEach(System.out::println);
Output:
a
b
c
5. From Stream.generate()
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
streamGenerated.forEach(System.out::println);
Output:
element
element
element
element
element
6. From Stream.iterate()
Stream<Integer> streamIterated = Stream.iterate(1, n -> n + 2).limit(5);
streamIterated.forEach(System.out::println);
Output:
1
3
5
7
9
7. Stream of File
Java NIO class Files allows to generate a Stream of a text file through the lines() method. Every line of the text becomes an element of the stream:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\file.txt");
Stream<String> streamOfStrings = Files.lines(path);
Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));
streamOfStrings.forEach(System.out::println);
streamWithCharset.forEach(System.out::println);
streamOfStrings.close();
streamWithCharset.close();
}
}
8. Stream of Primitives
As Stream is a generic interface and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Using the new interfaces alleviates unnecessary auto-boxing allows increased productivity:
import java.io.IOException;
import java.util.Random;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class StreamCreationExamples {
public static void main(String[] args) throws IOException {
IntStream intStream = IntStream.range(1, 3);
intStream.forEach(System.out::println);
LongStream longStream = LongStream.rangeClosed(1, 3);
longStream.forEach(System.out::println);
Random random = new Random();
DoubleStream doubleStream = random.doubles(3);
doubleStream.forEach(System.out::println);
}
}
Output:
1
2
1
2
3
0.6929414814363383
0.3683384343302385
0.948888698350225
Comments
Post a Comment
Leave Comment