Remove elements with Condition: greater than a certain value

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:

  1. Creating the ArrayList: We create an ArrayList named numbers and populate it with some integers.
  2. Defining the Max Value: We define the maxValue variable, which represents the threshold value. Elements greater than this value will be removed.
  3. Printing the Original List: We print the contents of the numbers list using System.out.println().
  4. Removing Elements Greater Than Max Value: We call the removeGreaterThan() method to remove elements greater than the maxValue. This method takes the ArrayList and the maxValue as parameters.
  5. removeGreaterThan() Method: This method uses an iterator to iterate through the elements of the ArrayList. If an element is greater than the, the iterator’s remove() method is called to remove that element from the list.
  6. Printing the Modified List: After removing elements greater than the maxValue, we print the contents of the modified numbers list using System.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.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *