How to filter an ArrayList in-place with Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
        
        // removeIf Method: It takes a lambda expression or a predicate as an argument. 
        // The predicate defines the condition for removal.
        // The removeIf method modifies the original list directly (In-place), 
        
        // Remove elements greater than 4
        numbers.removeIf(n -> n > 4);

        // Print the filtered list
        System.out.println(numbers); // Output: [1, 2, 3]
    }
}

    
/*
run:
           
[1, 2, 3, 4]
           
*/

 



answered Jul 13, 2025 by avibootz
...