top of page
Search

Java 8 - ArrayList removeIf

  • schick09
  • Aug 13, 2024
  • 1 min read

Java 8 added a new operation to the ArrayList class that will remove all elements from the list that match the given predicate supplied.


In the following example, we will create an ArrayList<String> containing the names of both foreign and American car makes. Then we will remove the "Honda" and "Toyota" makes from the list by using removeIf with a filter predicate, leaving only American made cars in the list.



        ArrayList<String> americanCars = new ArrayList<String>();
        americanCars.add("Toyota");
        americanCars.add("Ford");
        americanCars.add("Honda");
        americanCars.add("Chevrolet");
        americanCars.removeIf(car -> (car.equalsIgnoreCase("TOYOTA") || car.equalsIgnoreCase("HONDA")));
        americanCars.iterator().forEachRemaining((car) -> System.out.println(car));
    }
}

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


ree

 
 
 

Comments


Dave Schick Consulting

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

bottom of page