Java Streams

Maneesha Jayasundara
4 min readJul 4, 2021

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. Lets 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());
System.out.print(cubedNumbers);

The output that the we see here is :

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

2. Filter:

filter() method used to filter out the results as per our conditions. Now lets 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());
System.out.print(evenNumbers);

The output that the we see here is :

[2, 4, 6, 8, 10]

3. Sort:

Now if you wish to sort the given collection, 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());System.out.print(sortedList);

The output that the we see here is :

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

4. FlatMap:

flatMap() is used to convert 2 levels of stream into 1 level of 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())
.collect(Collectors.toList());
System.out.println(listOfAllIntegers);

The output that the we see here is :

[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()
.collect(Collectors.toList());
System.out.println(distinctCountries);
}

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.

Stream.of(1,2,3,4,5,6,7,8,9,0)
.filter(x -> x%2 ==0)
.peek(e -> System.out.println("The even numbers
are : " + e))
.collect(Collectors.toList());

The output that the we see here is :

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"))
.collect(Collectors.toList());
System.out.println(output);

The output that the we see here is :

[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"))
.count();
System.out.println(output);

The output that the we see here is :

2

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"));
System.out.println(areAllElementsStartingWithI);

Output:

false

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"));
System.out.println(areAllElementsStartingWithI);

The output that the we see here is :

true

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");listOfCountries.stream()
.filter(x-> x.toString().startsWith("I"))
.forEach(System.out::println);

Output:

India
Indonesia

Thank you !! 😊🙌

--

--