Streams in Java 8

Streams is a sequence of elements from a source that support data processing operations. You can think of them as Iterators over collection of data.

Stream Characteristics:

  • Sequence of elements: Like a collection, a stream provides an interface to a sequenced set of values of a specific element type
  • Source:Streams consume from a data providing source such as collections,arrays,or I/O resources.
  • Data processing operations:Streams support operations to manipulate data like filter,map,reduce,find.
  • Pipelining: Many Stream operations returns Stream themselves, which help us to chain operations to form larger streams
  • Internal Interation:When compared to collection we need to do iteration using method but in streams Iteration is done internally

Streams can be traversed only once:If you try to traverse same stream more than once you will get an error , see below

Output of above code

Streams has 2 operations:

1.Intermediate operations: Stream operations that can be connected are called intermediate operations, there return type is Stream only. Intermediate operation don’t perform any processing until a terminal operation is invoked.

2.Terminal operations: Terminal operation produces a result from a stream pipeline.Result of this operation is non stream value such as list,integer or void


Filtering and Slicing: Lets see how to filter a particular elements from a stream

With Predicate: As you know Stream has one filter method, which takes Predicate as an argument and returns a stream which has elements that matches the Predicate condition. Example:

This will filter and return list of all the employees which are active from all employees stream

Filtering with unique elements: This is combination of filtering and uniqueness, in this seeing below example we are first filtering for all the even numbers from the stream then on the returned stream we are applying distinct operation which fill result only unique even numbers from the stream

Truncating a stream: Stream can be truncated or can be reduced to a limit by specifying a size inside limit method(limit(n)) .If stream is ordered then first n elements are returned from stream

Mapping in Streams:

1.Applying a function to each element : Stream has a method map which takes function as an argument and applies that function to each element resulting a new element

Here map  is calling getEmpId() method for every employee and returning EmployeeIds for every object, We can use map when we want to perform some operation on every object of stream.

2.FlatMap : FlatMap lets you replace each value of stream with another stream and then concatenates all generated items into a single stream. In the below example where first we have used map operation in line 18 on Stream give us Array of String, whereas if we want to concatenate the result of every string array object we can use flatMap as in line 27

Above I have used Arrays.Stream method which returns stream of string from array objects like shown below

	String[] arr ={"h","e","l","l","o"}; :: println);

Finding and Matching:Sometime we have a use case where we need to find a element which matches a given property, we can do that by using allMatch ,anyMatch,noneMatch,findFirst,findAny methods of Stream. Lets see the syntax and how we can use each one of them

AllMatch: This method can be used where we want to match a criteria for every object present in stream,Example suppose we have list of students and we need to check that all students have cleared the exam ,so we can check like

AnyMatch: It is used to check if there is any element in stream that matches the certain condition.Example ,Like in previous case we checked if all students passed ,here we are checking if any failed ,AnyMatch will return true if any object in the stream passes the test.In below example if any student scored marks less than 40 , it will return true

noneMatch: noneMatch is the opposite of AllMatch.It ensures that no element in the stream matches the condition,as we checked in above example where students passed and scored marks greater than 40,we can check same thing with noneMatch by changing the condition, If no object matches with the predicate condition than it returns true

One important point to note here is that these operations allMatch, noneMatch, findFirst, and findAny are short-circuit operations i.e they don’t need to process whole stream in order to produce result

FindAny:FindAny is used when we need any random object from a stream of objects. Like in below example it will print any number from streams of numbers, FindAny will return an Optional type Object

You may also like...

Leave a Reply

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