A sneak peek into Java8 Stream Transformation and Terminal Operations

Reading Time: 3 minutes

Stream API was introduced in Java 8. It is used to process the collections of objects. With the help of Streams and Lambda functions, we can write clean, concise and understandable code.

Streams is pipeline of operations, which we can use to evaluate the data.

Streams have intermediate and terminal operations which we can use as per our requirement. Here’s a list of Operations:

Intermediate Operations: peek, flatMap, limit, sort, distinct, map, filter etc

Terminal Operations: noneMatch, allMatch, collect, findAny, findFirst, anyMatch, toArray, reduce, min, max, forEach, collect, count etc.

How do we create a Stream object?

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Stream<Integer> numberStream = numbers.stream();
Stream<Integer> newNumberStream = Stream.of(1,2,3,4,5,6,7,8,9,10);

Both the ways mentioned above provide us the stream object. Either we call the stream() method over the collection object or we pass the values directly to the Stream.of() method.

Lets see how the intermediate methods in the Streams Work:

  1. Map:

map() method is used to perform an operation over the collection list. Let’s see how can we create a list of cubes of the number provided in the given list.

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

List<Integer> cubedNumbers= numbers.stream()
.map(x -> x*x*x).collect(Collectors.toList());


The output that the we see here is :

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

2. Filter:

filter() method was used to filter out the results as per our conditions. Now let’s consider we want to filter out even numbers from the list of numbers from 1 to 10.

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

List<Integer> evenNumbers = numbers.stream()
.filter(x -> x%2==0).collect(Collectors.toList());


The output would be:

[2, 4, 6, 8, 10]

3. Sort:

Now if you wish to sort the given collection, Streams at your service!! You can use the sorted() method as an intermediate function for the sorting.

List<Integer> numbers = Arrays.asList(6,7,8,1,4,5,9,10,2,3);List<Integer> sortedList = numbers.stream().sorted().collect(Collectors.toList());


The output here would be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

4. FlatMap:

flatMap() is used to convert 2 levels of the stream into 1 level of the stream. In simple words, if we have a collection of ArrayList which consists of ArrayList, then with the help of flatMap() we can convert them into a single ArrayList.

List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(4,5,6);
List<Integer> list3 = Arrays.asList(7,8,9);

List<List<Integer>> listOfNumbers = Arrays.asList(list1, list2, list3);

List<Integer> listOfAllIntegers = listOfNumbers.stream()
.flatMap(x -> x.stream())


The output would be like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

5. Distinct:

If the given collection has duplicate items, we can use the distinct() method to remove the duplicate items and have a filtered collection.

List<String> countries = Arrays.asList("India", "Australia", "SriLanka","Russia", "Australia","SriLanka","India");

List<String> distinctCountries = countries.stream().distinct()

The Output here would be :

[India, Australia, SriLanka, Russia]

6. Peek:

peek() is an intermediate action. peek() returns a stream consisting of the elements of the traversed stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

peek() operation does nothing if we do not specify a terminal operation.

.filter(x -> x%2 ==0)
.peek(e -> System.out.println("The even numbers
are : " + e))

This provides the output :

The even numbers are : 2
The even numbers are : 4
The even numbers are : 6
The even numbers are : 8
The even numbers are : 0

Now lets have a look with the terminal operations:

  1. Collect:

collect() operation helps to collect the stream into a collection. This method takes a Collector implementation that provides useful reduction operations.

List listOfCountries = Arrays.asList("India", "Indonesia", "Nepal", "Afghanistan");

List output = (List) listOfCountries.stream()
.filter(x-> x.toString().startsWith("I"))

Output :

[India, Indonesia]

2. Count:

count() terminal operation helps us to find the count of the processed collection.

List listOfCountries = Arrays.asList("India", "Indonesia", "Nepal", "Afghanistan");

long output = listOfCountries.stream()
.filter(x-> x.toString().startsWith("I"))


Output :


3. AllMatch:

allMatch() operation helps us to get the answer: Do all the elements of the stream match the condition?

List listOfCountries = Arrays.asList("India", "Indonesia", "Nepal", "Afghanistan");

boolean areAllElementsStartingWithI = listOfCountries.stream()
.allMatch(x -> x.toString().startsWith("I"));




4. AnyMatch:

As compared to the allMatch() anyMatch() helps to check if either one of the elements in the stream matched the condition.

List listOfCountries = Arrays.asList("India", "Indonesia", "Nepal", "Afghanistan");

boolean areAllElementsStartingWithI = listOfCountries.stream()
.anyMatch(x -> x.toString().startsWith("I"));




5. ForEach:

forEach() method is used to iterate over the resultant collection, same as that of the traditional for loop.

List listOfCountries = Arrays.asList("India", "Indonesia", "Nepal", "Afghanistan");

.filter(x-> x.toString().startsWith("I"))



That was it!! Have fun using the streams very often henceforth!



Written by 

Munander is a Software Consultant in Knoldus Software LLP. He has done b.tech from IMS Engineering college, Ghaziabad. He has decent knowledge of C,C++,Java,Angular and Lagom. He always tries to explore new technologies. His hobbies include playing cricket and adventure.