Posts

Showing posts with the label Java8CollectionImprovements

Java 8 Iterator forEachRemaining method with code samples

Java 8 has added a method called forEachRemaning to the Iterator interface. This helps in using an Iterator to internally iterate over a Collection, without an explicit loop. In this article, I will be covering this method with a code sample. Edit Pre Java 8 code Before Java 8, you had to write code similar to the following in order to use an Iterator: public class ForEachRemainingDemo { public static void main(String[] args) { List<Integer> input = Arrays.asList(5, 3, 11, 15, 9, 2, 5, 11); Iterator<Integer> itr = input.iterator(); while(itr.hasNext()) System.out.println(itr.next()); }} So in this code, you need to use a while loop in order to use the iterator to iterate through the input list. Using Java 8 forEachRemaining Java 8 added the forEachRemanining method to the Iterator interface. So using this method, the above code can be re-written as follows: public class ForEachRemainingDemo { public static void main(String[] args) { List<Intege...