Stream Creation-Jav 8.0(JDK1.8)

Categories: Core Java Java 8(JDK1.8)

Stream Creation

There are many ways to create a stream instance of different sources. 

1.Empty Stream

2.Stream of Collection

3.Stream of Array

4.Stream.builder()

5.Stream.generate()

6.Stream.iterate()

7.Stream of Primitives

8.Stream of String

9.Stream of File

1. Empty Stream:- We should use the empty() method in case of the creation of an empty stream:

Stream<String> streamEmpty = Stream.empty();

We often use the empty() method 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. Stream of Collection

We can also create a stream of any type of Collection (Collection, List, Set):

Collection<String> collection = Arrays.asList("a", "b", "c");

Stream<String> streamOfCollection = collection.stream();

3. Stream of Array

An array can also be the source of a stream:

Stream<String> streamOfArray = Stream.of("a", "b", "c");

We can also create a stream out of an existing array or of part of an array:

String[] arr = new String[]{"a", "b", "c"};

Stream<String> streamOfArrayFull = Arrays.stream(arr);

Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);

4. Stream.builder()

When 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<Object>:

Stream<String> streamBuilder =

  Stream.<String>builder().add("a").add("b").add("c").build();

5. Stream.generate()

The generate() method accepts a Supplier<T> for element generation. As the resulting stream is infinite, the developer should specify the desired size, or the generate() method will work until it reaches the memory limit:

Stream<String> streamGenerated =  Stream.generate(() -> "element").limit(10);

The code above creates a sequence of ten strings with the value “element.”

6. Stream.iterate()

Another way of creating an infinite stream is by using the iterate() method:

Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);

The first element of the resulting stream is the first parameter of the iterate() method. When creating every following element, the specified function is applied to the previous element. In the example above the second element will be 42.

7. Stream of Primitives

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. 

As Stream<T> 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, which allows for increased productivity:

IntStream intStream = IntStream.range(1, 3);

LongStream longStream = LongStream.rangeClosed(1, 3);

The 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.

The rangeClosed(int startInclusive, int endInclusive) method does the same thing with only one difference, the second element is included. We can use these two methods to generate any of the three types of streams of primitives.

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 three elements:

Random random = new Random();

DoubleStream doubleStream = random.doubles(3);

8. Stream of String

We can also 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.

IntStream streamOfChars = "abc".chars();

The following example breaks a String into sub-strings according to specified RegEx:

Stream<String> streamOfString =  Pattern.compile(", ").splitAsStream("a, b, c");

9. Stream of File

Furthermore, Java NIO class Files allows us to generate a Stream<String> of a text file through the lines() method. Every line of the text becomes an element of the stream:

Path path = Paths.get("C:\\file.txt");

Stream<String> streamOfStrings = Files.lines(path);

Stream<String> streamWithCharset = 

  Files.lines(path, Charset.forName("UTF-8"));

The Charset can be specified as an argument of the lines() method

Top articles
Core Java Indroductions Published at:- Features of Java Published at:- Difference between Java and C Published at:- Difference between Java and C++ Published at:- Advantage and Disadvantage of Java Published at:- What is Java Published at:- Why Java is not Pure Object Oriented Language Published at:- Where and why Java is used Published at:- Java has Following Features Characteristics Published at:- Common Misconception about Java Published at:- 3 most commonly used tools are Published at:- Stream Creation-Jav 8.0(JDK1.8) Published at:- Data Type in Java-Size in Bytes & Bits . Published at:- Operators in Java-Assignment, increment and decrement, equality, arithmetic ,relational , logical, bit-wise, compound assignment Published at:- Java Control Flow of Statements Published at:- Java switch case and conditional operator Selection Statement Published at:- for and while Loop-Java Published at:- Java General Interview Questions and Answer Published at:- Write a program in Java to display the first 10 terms of the following series: 10, 20, 30, 40, …….. Published at:- Write the program in Java to display the first ten terms of the following series: 1, 4, 9, 16, Published at:- Write a program in Java to find the sum of the given series: Published at:- Write a program in Java to find the sum of the given series: Published at:- Why Proxies Are the Silent Backbone of Modern Online Operations Published at:-
R4Rin Team
The content on R4Rin.com website is created by expert teams.