Problem Statement: Write a Java program to remove all elements from an ArrayList that are greater than a certain value.
Here’s a Java program that demonstrates how to remove all elements from an ArrayList
that are greater than a certain value. I’ll provide an explanation of the program’s logic.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.Iterator;
public class RemoveElementsFromArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(25);
numbers.add(5);
numbers.add(15);
numbers.add(30);
numbers.add(20);
int maxValue = 20;
System.out.println("Original List: " + numbers);
// Removing elements greater than maxValue
removeGreaterThan(numbers, maxValue);
System.out.println("List after removing elements greater than " + maxValue + ": " + numbers);
}
// Method to remove elements greater than a given value
public static void removeGreaterThan(ArrayList<Integer> list, int value) {
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
if (iterator.next() > value) {
iterator.remove();
}
}
}
}
OUTPUT:
Original List: [10, 25, 5, 15, 30, 20]
List after removing elements greater than 20: [10, 5, 15, 20]
Explanation:
- Creating the ArrayList: We create an
ArrayList
namednumbers
and populate it with some integers. - Defining the Max Value: We define the
maxValue
variable, which represents the threshold value. Elements greater than this value will be removed. - Printing the Original List: We print the contents of the
numbers
list usingSystem.out.println()
. - Removing Elements Greater Than Max Value: We call the
removeGreaterThan()
method to remove elements greater than themaxValue
. This method takes theArrayList
and themaxValue
as parameters. removeGreaterThan()
Method: This method uses an iterator to iterate through the elements of theArrayList
. If an element is greater than the, the iterator’sremove()
method is called to remove that element from the list.- Printing the Modified List: After removing elements greater than the
maxValue
, we print the contents of the modifiednumbers
list usingSystem.out.println()
.
By using an iterator and the remove()
method, the program removes all elements from the ArrayList
that are greater than the specified value, effectively filtering out the unwanted elements.
See also: Sorting a List: Sort an ArrayList of integers.