Introduction to Java 8 Stream
The following article provides an outline for 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 forecasts 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 a 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 a stream consisting collection those methods include: forEach, map, filter, limit, etc.
How Stream Works in Java 8?
The normal stream concept in Java comprises of Input Stream and Output Stream respectively. But the introduction of the 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 that can process data in a declarative manner like 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 become easy and simplified using the stream of Java8.
Stream in java 8 defines an order and sequence for its data stream. The input is 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 below.
Characteristics of Java 8 Stream
Below are the characteristics of Java 8 Stream:
- 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 the stream takes collections, arrays, or I/O resources.
- Aggregation and Composition: Aggregation operation is being associated with the stream continuously which includes operations like filter, map, limit, reduce, etc.
- Iterations in an Automated Manner: Collections involve iteration which requires elements to operate externally but to perform iterations internally it involves and makes 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 use 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 Java 8 Stream
There are many methods involved for computation of each element 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 an easy switch between the sequential and parallel streams.
- Collectors: A 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 of Java 8 Stream
Given below are the examples of Java 8 Stream:
Example #1
This program is an example to illustrate lists, arrays, and 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 a list of components in an array, list, and lists, where the list components get converted into the 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 the uppercase array of alphabets using Java 8 Stream using a 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 Java. Streaming in Java 8 is completely different it makes use of a sequenced data structure which works as an abstract layer and then makes use of Java 8 streaming API which is used for the computation and generation of streams.
Recommended Articles
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. You can also go through our other suggested articles to learn more –