Introduction to Java 8 Stream
Stream is collection of some elements in an order from source that forms an aggregation where a source can be an array or collections which provides data to the stream. Java 8 streams also work with the same principle which means it is basically a prototype or data structure which will be organized and designed in a sequence to perform and manipulate data needed on demand. These streams are generated but is not visible to the end user which forecast that it is always performed in the background not in the foreground, but the activity does exist.
Syntax:
Generation of streams can be performed with collections using two methods of collection interface which is depicted as follows:
List<String> strings = Arrays.asList("abc", "" , "bc", "efgh" , "");
List<String> filtered = Strings.stream().filter(string - > !string.isEmpty()).collect(collectors.toList());
Associated Return types are as follows:
- stream(): It returns a sequence of stream with an order considering collection as source for the computation.
- parallelStream(): Returns of parallel stream which also consider collection as its prime root for computation to the list.
It consists of many other methods also which follow the generation of stream consisting collection those methods include: forEach, map, filter, limit, etc.
How Stream Works in Java 8?
Normal stream concept in Java comprises of Input Stream and Output Stream respectively. But the introduction of stream concept in java 8 supports and behaves in a different manner. It has its own perspective in terms of computation and manipulation. Streams introduced in Java 8 is a new abstract layer which can process data in a declarative mannerlike queries being performed for the SQL query or statements. Difficulty faced by developers using the collection frameworks or any other data structure creates the entire task of performing repeated checks and looping complex. Also, multi-core processors available for writing parallel code in the processor becomes easy and simplified using stream of Java8.
Stream in java 8 defines an order and sequence for its data stream. The input being feeded as an object which supports some operations related to aggregation and composition. These inputs being fed possess some characteristics and they are described as below:
Characteristics of Java 8 Stream
Below are the characteristics of Stream in java 8:
- Sequencing Stream: All the elements within the stream follows a sequence and an order which computes some elements on demand and never stores those elements in a conventional manner.
- Source: The data being fed as an input which means stream takes Collections, arrays, or I/O resources.
- Aggregation and Composition: Aggregation Operation Is being associated with the stream continuously which includes operation like filter, map, limit, reduce etc.
- Iterations in an Automated Mmanner: collections involve iteration which requires elements to operate externally but to perform iterations internally it involves and make use of source elements use to feed in the stream as an input.
- Pipelining: As its name suggests pipelining is a pattern where the streams generated gets returned by themselves and then they don’t return any output to the target. Moreover, it makes used of an intermediate operation to return the output after some computation. It also includes another method which is collect () method used for termination of the operations on the pipeline for stream generation and is generally found at the end of the entire pipeline flow.
Methods of Stream in java 8
There are many methods involved for computation of each elements of the stream like:
- For each: This method is used for iteration of elements of the stream.
- filter: The filter method is used to eliminate elements based on some conditions and constraints.
- Limit: This method is used to reduce the size of the element of the entire stream.
- Sorted: This method as part of the input stream functions in a way that it is used for sorting the stream in a manner.
- Parallel Processing: Parallel Processing has an alternative which is Parallel stream and involves easy switch between the sequential and parallel streams.
- Collectors: Combination of string is performed for processing of elements of a stream. It also returns a list or a string as a return type.
- Statistics: This is a special feature in addition to java 8 Streaming which is used to calculate all the stream statistics result.
Examples to Implement of Java 8 Stream
Below are the examples of Java 8 Stream:
Example #1
This program is an example to illustrate lists, arrays and the components before performing the Java Stream Expressions.
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Stream_Expression_Java {
public static void main(String[] args) {
List<String> lines = Arrays.asList("Science", "Chemistry", "Maths");
List<String> result = getFilterOutput(lines, "Maths");
for (String temp11 : result) {
System.out.println(temp11);
}
}
private static List<String> getFilterOutput(List<String> lines, String filter) {
List<String> result = new ArrayList<>();
for (String line : lines) {
if (!"Chemistry".equals(line)) {
result.add(line);
}
}
return result;
}
}
Output:
Example #2
This program illustrates the Java8 Streaming Expressions with list of components in an array, List and Lists, where the list components get converted into final output with the help of streaming and filtering.
Code:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Java8StreamingStarted {
public static void main(String[] args) {
List<String> lines = Arrays.asList("Walnut", "Apricot", "almond");
List<String> result = lines.stream()
.filter(line -> !"almond".equals(line))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
Output:
Example #3
This program is used to convert the normal list of Array of alphabets into uppercase array of alphabets using Java 8 Stream using map stream of collections.
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class java_8_Stream {
public static void main(String[] args) {
List<String> alphabets = Arrays.asList("p", "q", "r", "s");
List<String> alphabet_Upper = new ArrayList<>();
for (String s : alphabets) {
alphabet_Upper.add(s.toUpperCase());
}
System.out.println(alphabets);
System.out.println(alphabet_Upper);
List<String> collect = alphabets.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(collect);
List<Integer> num = Arrays.asList(3,4,5,6,7,8);
List<Integer> collect1 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(collect1);
}
}
Output:
Conclusion
Unlike the InputStream and OutputStream which functions for the Java. Streaming in Java 8 is completely different it makes use of sequenced data structure which works as an abstract layer and then makes use of Java 8 streaming API which is used for computation and generation of streams.
Recommended Article
This is a guide to Java 8 Stream. Here we discuss the Introduction and how Stream Works in Java 8 and its characteristics along with Examples and code implementation. You can also go through our other suggested articles to learn more –