streams in java guest post
Uncategorized

Streams in Java

In this article we are going to discuss one of the major pieces of new functionality Java 8 had added – Streams.

What is a stream?

Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In order to use Java Streams you need to import java.util.stream package.

The features of Java stream are:

  • A stream takes input from the Collections, Arrays or I/O channels and is not a data structure
  • Streams don’t change the original input they are provided with, they only provide the result as per the stream inbuilt methods of filtering, chaining etc.
  • Stream support sequential as well as parallel processing, which can be very helpful in achieving high performance in case of processing large collections. 

streams in java guest post

Stream Creation

There are different sources from which streams can be created for e.g. collections,  arrays etc.

String[] arr = new String[]{“hello”, “I am”, “stream”};

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

stream = Stream.of(“hello”, “I am”, “stream”);

Stream Operations

Let us see some of the useful operations which we can perform on streams.

The operations are categorized as

  1. Intermediate operations
  2. Terminal operations.

Intermediate operations allows chaining operations and return Stream<T> and terminal operations as the name suggests return a result of definite type. As I have mentioned earlier that operations on streams don’t change the input they are given.

Let’s see an example to understand:

long count = list.stream().distinct().count();

Iteration

Here we have used distinct and count methods in which distinct method acts as an intermediate operation and count method acts as a terminal operation there by returning the size of the list.

Stream provides a method called ‘forEach’ to iterate each and every element of the stream. Below code snippet prints 20 random numbers using forEach.

Random random = new Random();

random.ints().limit(20).forEach(System.out::println);

Mapping

The ‘map’ method given by stream is used to map each element to its corresponding result. Below code snippet prints unique squares of numbers using map.

List<Integer> numbers = Arrays.asList(4, 1, 1, 2, 6, 2, 4);

//get list of unique squares

List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

Matching

Stream API provides variety of methods for matching the elements of a sequence according to some predicate. These methods are

anyMatch(), allMatch(), noneMatch()

These all methods are terminal operations meaning they return a final result and in these cases a Boolean value.
boolean isValid = list.stream().anyMatch(element -> element.contains(“d”)); // true

boolean isValidOne = list.stream().allMatch(element -> element.contains(“d”)); // false

boolean isValidTwo = list.stream().noneMatch(element -> element.contains(“d”)); // false

Reduction

Stream API provides method for reducing the list of elements to some value according to a specified function using reduce() method.

This method requires two parameters

  1. Start value
  2. Accumulator function

For eg you have a List<Integer> and you want to have a sum of all the elements and an initial Integer ( 25). If you can run the following code the result will be 28 as 25 will be the initial value and 1 will be added 3 times as we have used the expression a + b here.
List<Integer> integers = Arrays.asList(1, 1, 1);

Integer reduced = integers.stream().reduce(25, (a, b) -> a + b);

Filter

The ‘filter’ method in the Stream API is there to exclude the elements based on a condition. The following snippet filters the list based on names starting with ‘S’;

List names = Arrays.asList(“Sandeep”,”Himanshu”,”Rohit”);

List result = names.stream().

filter(s->s.startsWith(“S”)).collect(Collectors.toList());

In this article, we have gone through the various methods that can be used in the Java Streams. The goal of this article was to give you an introduction about Java Streams so that you can start programming with new concepts of streams.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top