Operations in Java Streams

Reading Time: 3 minutes

Hi guys, with release of Java 8 we get new features like lambda functions, streams etc. and in this blog we are going to have an overview of Streams.
Streams reduces the effort for using and accessing the elements in any Collection. So here we will see what are different types of operation in Streams and when to use them.

Streams Definition

Streams are used when we have to process collections of objects. A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result.

A Java Stream is a component that is capable of internal iteration of its elements, meaning it can iterate its elements itself.

Types Of Operations in Streams

There are two types of operations in streams, some operations produce another stream as a result and some operations produce non-stream values as a result.
So we can say that stream interface has a selection of terminal and non-terminal operations.

1 . Non-Terminal/ Intermediate Operation

The operations which return another stream as a result are called intermediate operations.
 Types Of Intermediate Operation:

map(): The map method is used to returns a stream consisting of the results of applying the given function to the elements of this stream. It is used to transform each element of the stream by applying a function to each element.
For example, if you have a list of String and you want to convert all of them into upper case.

List name = Arrays.asList("amar","ujala");
List capitalName = number.stream().map(name->name.toUpperCase()).collect(Collectors.toList());

Output:
[AMAR, UJALA]

filter(): The filter method is used to perform filtering based upon some boolean conditions.
For example,  if you have a stream of integral numbers which contains both even and odd numbers then by using the filter method, you can create another stream of even numbers or odd numbers by filtering out others.

List number = Arrays.asList(1,2,3,4,5,6);
List evenList = number.stream().filter(number->number%2==0).collect(Collectors.toList());

Output:
[2, 4, 6]

sorted(): The sorted method is used to sort or arrange the list.
For example,  if you have an unorganized list of food items and you want to see all items arranged in Alphabetical order.

List names = Arrays.asList("Shawarma","Lobster","Cup Cakes");
List result = names.stream().sorted().collect(Collectors.toList());

Output:
[Cup Cakes, Lobster, Shawarma]

Rest of Intermediate Operations are:

  • flatMap()
  • distinct()
  • peek()
  • limit()
  • skip()

2. Terminal Operation

The operations which return non-stream values like primitive or object or collection or return nothing are called terminal operations.
 Types Of Terminal Operation:

collect(): The collect method is used to return the result of the intermediate operations performed on the stream. This method allows you to accumulate the result into the choice of the container you want. Like, a list, set, or a map.
For example, suppose you want to have sqaure of the age of all the students in a class. Then you can first operate map() method and then can get the result in a set by using the collect() method.

List ages = Arrays.asList(2,6,3,4,5,3);
Set square = ages.stream().map(age->age*age).collect(Collectors.toSet());

Output:
[16, 4, 36, 9, 25]

forEach(): The forEach method is used to iterate through every element of the stream.
For example, suppose you want to print the age of students in a class, 2 years from now. But you don’t want actual list to be modified.

List ages = Arrays.asList(12,13,11,14,15);
ages.stream().forEach(age->System.out.println(age+2));

Output:
14
15
13
16
17

reduce(): The reduce method is used to reduce the elements of a stream to a single value.
The reduce method takes a BinaryOperator as a parameter.
For example, suppose you want to calculate the sum of all the numbers in a list.

List number = Arrays.asList(2,3,4,5,6);
int sum = number.stream().reduce(0,(ans,i)-> ans+i); //Here ans variable is assigned 0 as the initial value and i is added to it .

Output:
20

Rest of Terminal Operations are:

  • toArray()
  • count()
  • forEachOrdered()
  • min()
  • max()
  • anyMatch()
  • allMatch()
  • noneMatch()
  • findAny()
  • findFirst()

Conclusion

  • A stream is not a data structure. It takes input from the Collections, Arrays or I/O channels.
  • Streams don’t interfere with the original data structure, they only provide the result as per the methods.
  • Streams are used for computing the elements as per the methods without altering the original value of the object.

References

Written by 

I am a genius middle-class noble philanthropist(by heart) . & Simply a technology enthusiast who loves to share and gain knowledge through blogs.

2 thoughts on “Operations in Java Streams4 min read

  1. There are plenty of mistakes in the examples. Like mixing the description and the code snippets.
    Just one of many:
    For example, if you have a list of String and you want to convert all of them into upper case.

    List number = Arrays.asList(1,2,3,4,5);
    List square = number.stream().map(x->x*x).collect(Collectors.toList());

    Output:
    [1, 4, 9, 16, 25]

    1. Thanks for your comment. Your comments help us to continuously improve.
      Initially the intention was to discuss any use-case and give a general example.
      However it seems like it wasn’t coming out that way. The blog has been updated.
      We would love to hear from you again. Thank You.

Comments are closed.