Skip to main content

Posts

Showing posts from February, 2018

[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);

[Java 8] what's new - Foreach

I recently moved to Java 8 and found some interesting feature added with Java 8. I have listed few of them: 1. forEach method - Apply on all First we will go through forEach method. Create a dummy collection List < Integer > iList = new ArrayList < Integer >(); for ( int i = 0 ; i < 100 ; i ++) iList . add ( i ); Without Foreach Iterator < Integer > itr = iList . iterator (); while ( itr . hasNext ()){ System . out . println ( "Value:" + itr.next() ); } With Foreach iList . forEach ( new Consumer < Integer >() { public void accept ( Integer i ) { System . out . println ( "Value::" +i ); } }); You might see not much change in term of line of code. What important thing to note here clear separation between business and iteration. You can easily write your code As we apply operation on collection, we are prone to ConcurrentModificationException if we wrongly operate on iter