Skip to main content

[Java8] Stream APIs

I recently moved to Java 8 and found some interesting feature added with Java 8.



Stream APIs
We will go through Stream apis added with Java collections. Stream api have sequential and parallel operation. We can apply these operation for filer/map/reduce/collect/flatmap. This is certainly helpful applying bulk operation on Collection. Besides parallel execution comes very handy with multi-core systems.

Lets see by an example. Create a dummy collection


  List<Integer> iList = new ArrayList<Integer>();
  for(int i=0; i<100; i++) iList.add(i);
Sequential Stream:


Stream<Integer> sequentialStream = iList.stream();
 sequentialStream.filter( i -> (i%2 == 0) ).forEach(System.out.println);
Parallel Stream:


Stream<Integer> parallelStream = myList.parallelStream();
 parallelStream.filter(i -> (i % 2 != 0 )).forEach(System.out.println);

Comments