Skip to content
CodeKruPro

Removing from a list inside for-each

Predict the outputMedium-HardJava onlyAsked in: Capgemini, Wipro
Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("a", "b", "c", "d"));
        for (String s : names) {
            System.out.println(s);
            if (s.equals("a")) {
                names.remove(s);
            }
        }
        System.out.println(names);
    }
}

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in