Wednesday, March 19, 2014

2 Examples of Streams with Collections in Java 8

Finally Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting feature. Though Lambda expression is the most talked item of coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API were not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allow you to process elements of Java Collections in parallel. Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of orders, you can filter buy orders with sell orders, filter orders based upon there quantity and price and so on. You can also perform two of most popular functional programming functions e.g. map and reduce. java.util.stream class provides function such mapToInt(), mapToLong(), and map function to apply an operation on all elements of Collections. By the way, these are just few of gems of Stream API, I am sure you will find several more, when you start exploring lambda expression and java.util.stream package. In this tutorial, we will see 2 examples of using Java 8 Stream with Collections classes. I have chosen List for these example, but you can use any Collection e.g. Set, LinkedList etc. By the way, use of Stream is not limited to Collections only, you can even use an array, a generator function, or an I/O channel as source. In most cases, a Stream pipeline in Java 8 consists a source, followed by zero or more intermediate stream operations e.g. filter() or map(); and a terminal operation such as forEach() or reduce().
Read more �

No comments:

Post a Comment