Streams In Java
Streams
Stream is an abstract layer, which is newly introduced in Java 8. With the help of stream, we can process the data in a declarative way similar to SQL statements.
For example
SELECT student_id, student_name FROM Student
This SQL statement automatically returns the student's details without doing any calculation on the programmer's end. By using collections framework, a programmer has to use loops and make repeated checks.
To resolve these types of issues, Java 8 introduced the concept of stream, which lets the programmer to process the data declaratively and influence multi-core architecture without the need to write any specific code for it.
Stream
Stream represents a sequence of objects from a source, which supports the aggregate operations.
Characteristics of a Stream
Sequence of elements − A stream gives a set of elements of a particular type in a sequential manner. A stream gets the elements on demand and it never stores the elements.
Source − Stream takes collections, arrays and I/O resources as an input source.
Aggregate operations − Stream holds the aggregate operations like filter, map, reduce, match etc.
Pipelining − Many stream operations return stream itself. Thus, their result can be pipelined. These operations are known as intermediate operations and their function are to take input, process them and return output to the target. The collect() method is a terminal operation, which is usually present at the end of the pipelining operation to mark the end of the stream.
Automatic iterations – A stream operations perform the iterations internally over the source elements provided and are in contrast to collections, where explicit iteration is required.
Generating Streams
In Java 8, collection interface has two methods to make a stream, which are,
stream() – This method is used to return a sequential stream consider collection as its source.
parallelStream() – This method is used to return a parallel stream, which considers collection as its source.
Some other important terms
forEach
Stream provides a new method ‘forEach’ to iterate each element of the stream.
map
The ‘map’ method maps each element to its corresponding result.
filter
The ‘filter’ method eliminates the elements, based on the criteria.
limit
The ‘limit’ method reduces the size of the stream.
sorted
The ‘sorted’ method sorts the stream.
Parallel Processing
For parallel processing, parallel stream is the alternative of stream and we can easily switch between the sequential streams and the parallel streams.
Collectors
Collectors combine the result of processing on the elements of a stream and it can be used to return a list or a string.
Statistics
Statistics collectors are used to calculate all the statistics, if the stream processing is being done.
Let’s see an example of streams, given below.
Code
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.IntSummaryStatistics;
- import java.util.List;
- import java.util.Random;
- import java.util.stream.Collectors;
- import java.util.Map;
- public class StreamsExample {
- public static void main(String args[]) {
- System.out.println("Java 7");
- List < String > strings = Arrays.asList("mia", "", "hi", "sam", "jack");
- System.out.println("List: " + strings);
- long count = getCountEmptyStringUsingJava7(strings);
- System.out.println("Null Strings: " + count);
- count = getCountLength3UsingJava7(strings);
- System.out.println("Strings of length 3: " + count);
- List < String > filtered = deleteEmptyStringsUsingJava7(strings);
- System.out.println("Filter List: " + filtered);
- String mergedString = getMergedStringUsingJava7(strings, ", ");
- System.out.println("Combined String: " + mergedString);
- List < Integer > numbers = Arrays.asList(3, 2, 2, 5);
- List < Integer > squaresList = getSquares(numbers);
- System.out.println("Squares List: " + squaresList);
- List < Integer > integers = Arrays.asList(1, 2, 13, 4);
- System.out.println("List: " + integers);
- System.out.println("Highest number : " + getMax(integers));
- System.out.println("Lowest number : " + getMin(integers));
- System.out.println("Sum of numbers : " + getSum(integers));
- System.out.println("Average of numbers : " + getAverage(integers));
- System.out.println("Random Numbers: ");
- Random random = new Random();
- for (int i = 0; i < 10; i++) {
- System.out.println(random.nextInt());
- }
- System.out.println("Java 8");
- System.out.println("List: " + strings);
- count = strings.stream().filter(string - > string.isEmpty()).count();
- System.out.println("Null Strings: " + count);
- count = strings.stream().filter(string - > string.length() == 3).count();
- System.out.println("Strings of length 3: " + count);
- filtered = strings.stream().filter(string - > !string.isEmpty()).collect(Collectors.toList());
- System.out.println("Filter List: " + filtered);
- mergedString = strings.stream().filter(string - > !string.isEmpty()).collect(Collectors.joining(", "));
- System.out.println("Combined String: " + mergedString);
- squaresList = numbers.stream().map(i - > i * i).distinct().collect(Collectors.toList());
- System.out.println("Squares List: " + squaresList);
- System.out.println("List: " + integers);
- IntSummaryStatistics stats = integers.stream().mapToInt((x) - > x).summaryStatistics();
- System.out.println("Highest number : " + stats.getMax());
- System.out.println("Lowest number : " + stats.getMin());
- System.out.println("Sum of numbers : " + stats.getSum());
- System.out.println("Average of numbers : " + stats.getAverage());
- System.out.println("Random Numbers: ");
- random.ints().limit(10).sorted().forEach(System.out::println);
- //parallel processing
- count = strings.parallelStream().filter(string - > string.isEmpty()).count();
- System.out.println("Empty Strings: " + count);
- }
- private static int getCountEmptyStringUsingJava7(List < String > strings) {
- int count = 0;
- for (String string: strings) {
- if (string.isEmpty()) {
- count++;
- }
- }
- return count;
- }
- private static int getCountLength3UsingJava7(List < String > strings) {
- int count = 0;
- for (String string: strings) {
- if (string.length() == 3) {
- count++;
- }
- }
- return count;
- }
- private static List < String > deleteEmptyStringsUsingJava7(List < String > strings) {
- List < String > filteredList = new ArrayList < String > ();
- for (String string: strings) {
- if (!string.isEmpty()) {
- filteredList.add(string);
- }
- }
- return filteredList;
- }
- private static String getMergedStringUsingJava7(List < String > strings, String separator) {
- StringBuilder stringBuilder = new StringBuilder();
- for (String string: strings) {
- if (!string.isEmpty()) {
- stringBuilder.append(string);
- stringBuilder.append(separator);
- }
- }
- String mergedString = stringBuilder.toString();
- return mergedString.substring(0, mergedString.length() - 2);
- }
- private static List < Integer > getSquares(List < Integer > numbers) {
- List < Integer > squaresList = new ArrayList < Integer > ();
- for (Integer number: numbers) {
- Integer square = new Integer(number.intValue() * number.intValue());
- if (!squaresList.contains(square)) {
- squaresList.add(square);
- }
- }
- return squaresList;
- }
- private static int getMax(List < Integer > numbers) {
- int max = numbers.get(0);
- for (int i = 1; i < numbers.size(); i++) {
- Integer number = numbers.get(i);
- if (number.intValue() > max) {
- max = number.intValue();
- }
- }
- return max;
- }
- private static int getMin(List < Integer > numbers) {
- int min = numbers.get(0);
- for (int i = 1; i < numbers.size(); i++) {
- Integer number = numbers.get(i);
- if (number.intValue() < min) {
- min = number.intValue();
- }
- }
- return min;
- }
- private static int getSum(List numbers) {
- int sum = (int)(numbers.get(0));
- for (int i = 1; i < numbers.size(); i++) {
- sum += (int) numbers.get(i);
- }
- return sum;
- }
- private static int getAverage(List < Integer > numbers) {
- return getSum(numbers) / numbers.size();
- }
- }
Output
Summary
Thus, we learnt that the stream is an abstract layer, which is newly introduced in Java 8. With the help of stream, we can process the data in a declarative way similar to SQL statements and also learnt how to use it in Java.