In this article, we will discuss 8 different ways of creating a Stream object in Java 8.
There are many ways to create a stream instance of different sources such as Collections, Arrays, File etc. Once created, the instance will not modify its source, therefore allowing the creation of multiple instances from a single source.
If you are new to Java 8 Stream API then you may read our article on Java 8 Stream API.
If you are new to Java 8 Stream API then you may read our article on Java 8 Stream API.
1. Empty Stream
The empty() method should be used in case of a 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
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 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
Related Java 8 Top Posts
- Java 8 Lambda Expressions
- Java 8 Functional Interfaces
- Java 8 Method References
- Java 8 Stream API
- Java 8 Optional Class
- Java 8 Collectors Class
- Java 8 StringJoiner Class
- Java 8 Static and Default Methods in Interface
- Guide to Java 8 forEach Method
- Handle NullPointerException using Java 8 Optional Class
- How to Use Java 8 Stream API in Java Projects
- Migrating Source Code to Java 8
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment