Java 8 – Stream API and its benefits with simple examples

  • Stream API ( java.util.stream ) is a new feature introduced in Java 8, which allows parallel or serial operations on Collections
  • Collection interface provides default methods stream() and parallelStream() which returns the Stream object
  • Stream object allows operations such as filter, map, reduce, find, match , sort etc
  • Parallel streaming makes use of new ForkJoinPool introduced in Java 8 which leverages available CPU cores to achieve parallelism and thereby performance

Example

 

OUTPUT

Bag(0kg) Bag(2kg) Bag(4kg) Bag(6kg) Bag(8kg)
sum of even weight bags = 20
Bag(6kg) Bag(8kg) Bag(2kg) Bag(0kg) Bag(4kg)

 

Code explained

Add bags with weights to list
1) get sequential stream using stream(), filter to get even weight bags , print using forEach and method reference
2) get sequential stream using stream(), filter to get even weight bags , get integer stream using mapToInt(ToIntFunction<T>) and get sum using sum()
3) get parallel stream using paralleStream(), filter to get even weight bags , print using forEach and method reference

Note : filter, map, reduce , sort etc are Intermediate functions which return again a Stream and forEach, sum() etc are Terminal functions which return either value or nothing.

 

References

Java 8 – new features and enhancements with examples

Stream API docs

 

Author of CodeForEach.com . Loves coding and related technologies.
 

www.000webhost.com