Java SE 8 introduces a new package which allows to perform filter (or) map (or) reduce like operations with the collections in Java. The helps us to do bulk data operations. As we acquire a stream instance, we can perform interesting tasks with collections.

In simple words, a Stream is something like an iterator.

Let’s look at below example

Example : Filtering a list of student names starting with “A” in prior versions of java.

There is nothing special about this code. This is a traditional Java external iterations example.

Output: List of names starting With A : [Arvind, Anand, Anamika]

Now, have a look at the below code. This line is doing exactly the same thing but we can’t see any iteration logic here and hence it is called as internal iterations.

Output: List of names starting With A : [Arvind, Anand, Anamika]

Stream Operations: are used to described the transformations that should be performed over the stream of data. The filter(..) and map(..) methods in the good examples of intermediate operations. The return type of

these methods is stream, so that it would allow chaining of more operations.Here’s a list of some useful intermediate operations:

  • filter excludes all elements that don’t match a Predicate.
  • map perform transformation of elements using a Function.
  • peek perform some action on each element as it is encountered.
  • distinct excludes all duplicate elements according to their equals(..)behavior.
  • sorted ensures that stream elements in subsequent operations are encountered according to the order imposed by a Comparator.
  • limit ensures that subsequent operations only see up to a maximum number of elements.
  • substream ensure that subsequent operations only see a range (by index) of elements.

Let’s look at below for various functions of stream:

Output :

  • List has 2 empty strings
  • List without empty Strings : [Raju, Anand, Sravika, Shilpa]
  • Uppercase name list : [RAJU, ANAND, SRAVIKA, SHILPA]
  • Square Without duplicates : [256, 81, 9, 64, 169, 25]
  • Highest number : 27
  • Lowest number : 5
  • Sum of numbers : 109
  • Average of numbers : 5

Stream is going to be hugely popular among Java developers, given it’s supports of functional programming idioms such as map and support for filtering elements from Collection. That’s all about how to use Streams with Collections in Java 8 we will come across much more examples in future articles.