Skip to content
Advertisement

How to remove an element and the element after that in an ArrayList if the value of the element is less than a specific integer?

I have this program where I need to remove the value from an ArrayList and the value after that if the value is less than 10.

Here is an example:

Original ArrayList:

[20, 40, 15, 4, 25, 50, 45]

Modified ArrayList: (if the value is less than 10)

[20, 40, 15, 50, 45] – (Removed 4 and 25 because 4 is less than 10)

I have made a program that remove the value that is less than 10, but I can’t figure out how to remove the second value as well.

I have tried to create a variable boolean restart that is set to true if the for-each loop removes the value that is less than 10. But I’m stuck.

Here is my code:

Scanner sc = new Scanner(System.in);

    int numberOfMeasurements = sc.nextInt();
    boolean restart = false;

    ArrayList<Integer> measurements = new ArrayList<Integer>();

    for(int i = 0; i < numberOfMeasurements; i++) { 
        measurements.add(sc.nextInt());
    }

    ArrayList<Integer> measurementsTwo = new ArrayList<>();
    for (int i : measurements) {
        if (i > 10) {
            measurementsTwo.add(i);
            restart = true;
        }
    }
    measurements = measurementsTwo;

    System.out.println(measurements);

If the description is imprecise just say it, and I will try to clarify my problem.

Advertisement

Answer

A good old iterator should do:

for (Iterator<Integer> it = measurements.iterator(); it.hasNext();) {
    if (it.next() < 10) {
        it.remove();
        if (it.hasNext()) { // ensures no failure if `it` was at last element
            it.next();
            it.remove();
        }
    }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement