First, it may be needed to make sure that the input list contains at least num
occurrences of the needed elements, that is, the appropriate indexes should be tracked and as soon as the num
elements is detected, the elements at these indexes are removed:
public static void removeNFirst(ArrayList<Integer> list, int num, int element) {
int[] indexes = IntStream.range(0, list.size())
.filter(i -> list.get(i) == element)
.limit(num)
.toArray();
// make sure at least num elements are found
if (indexes.length < num) {
return;
}
for (int i = indexes.length; i-- > 0; ) {
list.remove(indexes[i]);
}
}
Test:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 1, 2, 1, 3));
System.out.println("Initial: " + list);
removeNFirst(list, 3, 1);
System.out.println("Removed three first 1: " + list);
removeNFirst(list, 2, 2);
System.out.println("Removed two first 2: " + list);
Output:
Initial: [1, 2, 1, 2, 1, 3]
Removed three first 1: [2, 2, 3]
Removed two first 2: [3]