top of page
Search

Java 8 - Iterator forEachRemaining

  • schick09
  • Aug 14, 2024
  • 1 min read

Java 8 introduced a new method to Iterator called forEachRemaining. This method takes a Consumer, which represents an operation that acceps a single input argument and returns no result.


Here's one way we used to iterate over a collection before this method was introduced:



public class Main {
    public static void main (String[] args){
        List<String> cars = new ArrayList<>();
        cars.add("Honda");
        cars.add("Toyota");
        cars.add("Ford");
        cars.add("Subaru");
        Iterator<String> iterator = cars.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
}




With forEachRemaining, we can now perform the equivalent logic with a single line of code like so:


public class Main {
    public static void main (String[] args){
        List<String> cars = new ArrayList<>();
        cars.add("Honda");
        cars.add("Toyota");
        cars.add("Ford");
        cars.add("Subaru");
        cars.iterator().forEachRemaining((car) -> System.out.println(car));}

}


Here's a link to our GitHub location to access an example of using the Iterator forEachRemaining operation: https://github.com/daveschickconsulting/java_8_examples/tree/main/src/funwithforeachremaining



ree

 
 
 

Comments


Dave Schick Consulting

©2023 by Dave Schick Consulting. Proudly created with Wix.com

bottom of page