logo

Streams


Show

Stream may be a new conceptual layer introduced in Java 8. Using stream, you'll process data in a declarative way almost like SQL statements. For instance, consider the subsequent SQL statement.

SELECT max(salary), employee_id, employee_name FROM Employee

The above-given SQL expression automatically returns the utmost salaried employee's details, without doing any computation on the developer's end. With the help of a collections framework in Java, a developer has got to know and use loops and regularly makes repeated checks. Another concern is efficiency; as multi-core processors are available comfortably, a Java developer has got to write parallel code processing which will be pretty error-prone.

To solve this problem, Java 8 launched the concept of the stream that lets the developer process data declaratively and grip multicore architecture without writing down any specific code for it.

What is Stream?

A stream represents an order of objects from a source, which assists in aggregating the operations. Below are some characteristics of a Stream −

  • A sequence of elements − A stream provides a group of elements of a specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the weather.
  • Source − Stream gets hold of Collections, Arrays, or I/O resources as the input source.
  • Aggregate operations − Stream supports in aggregating the operations like map, reduce, filter, find, limit, match, and so on.
  • Pipelining − Most of the stream operations return stream itself in order that their results are often pipelined. These operations are known as intermediate operations and their function is to require input, now process them, and return output to the target. Collect() method may be a terminal operation that is generally present at the top of the pipelining operation to mark the top of the stream.
  • Automatic iterations − Stream operations do the iterations internally over the many source elements provided, in contrast to Collections where explicit iteration is required.

How to Generate Streams:

With the Collection of interfaces in Java 8, there are two methods to generate a stream

  • Stream(): It is the Collection of source returns of sequential streams.
  • Parallel Stream(): Returning parallel streams are considered as the collection of its sources.
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

forEach

It is the new method provided by stream to iterate every single Element of the stream. The below-given code segment shows how to print 10 random numbers using forEach.

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

Map

The ‘map’ method is employed to map each element to its corresponding result. This subsequent code section prints unique squares of numbers by using a map option in Stream.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

Filter

The ‘filter’ method is employed to eliminate elements supporting criteria. The subsequent code segment prints a count of empty strings using a filter.

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
int count = strings.stream().filter(string -> string.isEmpty()).count();

Limit

The ‘limit’ method is employed to scale back the dimensions of the stream. The subsequent code segment shows the way to print 10 random numbers using the limit.

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

Sorted

The ‘sorted’ method is employed to sort the stream. The subsequent code segment shows the way to print 10 random numbers during a sorted order.

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

Parallel Processing

ParallelStream is an alternative stream for multiprocessing. Now, Take a glimpse at the subsequent code segment that prints a sum-up of empty strings using parallelStream.

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
//get count of empty string
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

You can easily switch between sequential and parallel Streams.

Collectors

Collectors are wont to combine the results of processing on the weather of a stream. Collectors are often wont to return an inventory or a string.

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("Filtered List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged String: " + mergedString);

Statistics

In Java 8 statistics collectors are initiate to calculate all statistics when stream processing is done

List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest number in List : " + stats.getMax());
System.out.println("Lowest number in List : " + stats.getMin());
System.out.println("Sum of all numbers : " + stats.getSum());
System.out.println("Average of all numbers : " + stats.getAverage());

Example of Stream

You can create the given java program by using any editor you are favorable within, say, C:\> JAVA.

Java8Tester.java

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 Java8Tester {

   public static void main(String args[]) {
      System.out.println("Using Java 7: ");
		
      // Count empty strings
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      System.out.println("List: " +strings);
      long count = getCountEmptyStringUsingJava7(strings);
		
      System.out.println("Empty Strings: " + count);
      count = getCountLength3UsingJava7(strings);
		
      System.out.println("Strings of length 3: " + count);
		
      //Eliminate empty string
      List<String> filtered = deleteEmptyStringsUsingJava7(strings);
      System.out.println("Filtered List: " + filtered);
		
      //Eliminate empty string and join using comma.
      String mergedString = getMergedStringUsingJava7(strings,", ");
      System.out.println("Merged String: " + mergedString);
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
		
      //get list of square of distinct numbers
      List<Integer> squaresList = getSquares(numbers);
      System.out.println("Squares List: " + squaresList);
      List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
		
      System.out.println("List: " +integers);
      System.out.println("Highest number in List : " + getMax(integers));
      System.out.println("Lowest number in List : " + getMin(integers));
      System.out.println("Sum of all numbers : " + getSum(integers));
      System.out.println("Average of all numbers : " + getAverage(integers));
      System.out.println("Random Numbers: ");
		
      //print ten random numbers
      Random random = new Random();
		
      for(int i = 0; i < 10; i++) {
         System.out.println(random.nextInt());
      }
		
      System.out.println("Using Java 8: ");
      System.out.println("List: " +strings);
		
      count = strings.stream().filter(string->string.isEmpty()).count();
      System.out.println("Empty 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("Filtered List: " + filtered);
		
      mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
      System.out.println("Merged 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 in List : " + stats.getMax());
      System.out.println("Lowest number in List : " + stats.getMin());
      System.out.println("Sum of all numbers : " + stats.getSum());
      System.out.println("Average of all 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.