I recently moved to Java 8 and found some interesting feature added with Java 8.
I have listed few of them:
Create a dummy collection
With Foreach
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 iterator. Foreach help with that operation.
Comments
Post a Comment