1

I have an ArrayList and I have to remove the first 2 instances of number 1

public void remove(int num, int element) {

    ArrayList<Integer> arr = [1, 2, 1, 2, 1];
    // ...
}

element is the number inside myArray, num is how many times I have to remove the element.

So if num is 2 and element is 1, the ArrayList will contain [2, 2, 1]

How can I do it? I've tried a for loop but I don't know how to write the 'how many times'. Thank you

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42

5 Answers5

3

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]
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • but it will not be always remove two elements, the number of elements of a specific type that needs to be removed is also passed as an argument to the method – Gurkirat Singh Guliani Jan 23 '22 at 00:36
  • 1
    @GurkiratSinghGuliani, yes, the title of the question misled me a bit, so the updated answer removes exactly `num` matching elements. – Nowhere Man Jan 23 '22 at 00:50
  • 1
    Well, if you know for sure that `num` is always two, you can simply use `list.remove((Object)element); list.remove((Object)element);` For an arbitrary `num`, I’d replace `toArray()` with `reduce((a,b) -> b)` to find the index of the last element to remove, followed by `list.subList(0, lastToRemove + 1).removeIf(o -> o == element);` as this avoids copying the remaining elements `num` times. – Holger Jan 24 '22 at 09:23
2

SHORT ANSWER TO YOUR QUESTION:

You can keep on reducing the number till it reaches 0. If the number matches the element, then you can remove it.

QUESTION THAT NEEDS TO BE THOUGHT UPON:

What to do in case the number of elements to be removed are more than those present in the list . for example in case of your array, what if it had been element 1 to be removed more than 4 times.

SAMPLE SOLUTION:

The logic i'm providing below works for the case when the number of elements to be removed are always less than or equal to the elements present in the list.

public class Swtich {
    public static void main(String[] args) {

        remove(2,1);
    }

    public static void remove(int num, int element) {

        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(1);
        arr.add(2);
        arr.add(1);

        System.out.println(arr);
        int i = 0;

        while (num > 0) {
//          System.out.println(arr);
            if (arr.get(i) == element) {
                arr.remove(i);
                num--;
            } else {
                i++;
            }
        }

        System.out.println(arr);
    }
}

and the output is as follows :

[1, 2, 1, 2, 1]
[2, 2, 1]
Gurkirat Singh Guliani
  • 1,009
  • 1
  • 4
  • 19
1
public static void remove(ArrayList arr, int num, int element){
    int removeCounter = 0;
    while (removeCounter != num) {
        arr.remove(arr.indexOf(element));
        removeCounter++;
}

You can use a counter like in my code... Also you should create ArrayList outside of the method block so you can print it in main method.

T1000
  • 11
  • 1
1

Combine an iterator with an counter.

public void remove(int num, int element) {
    ArrayList<Integer> arr = [1, 2, 1, 2, 1];
    Iterator<Integer> arrIterator = arr.iterator();
    int count = 0;
    while(arrIterator.hasNext() && num > count) {
        if (arrIterator.next().equals(element)) {
            arrIterator.remove();
            count++;
        }
    }
}
magicmn
  • 1,787
  • 7
  • 15
  • `ArrayList arr = [1, 2, 1, 2, 1];` Never seen that syntax before and can't find any mention of it in documentation? – Shawn Jan 23 '22 at 02:40
  • I copied it from his example. Very unlikely this will actually compile, but if you want to make sure ask OP. – magicmn Jan 23 '22 at 07:54
0

Call remove(Object), which removes the first instance found, n times:

Integer numberToRemove = 1; // note: must be Integer
for (int i = 0; i < n; i++) { 
    arr.remove(numberToRemove);
}

Note that for List<Integer>, you must remove an Integer, otherwise the remove(int)` method will be called which removes the element at position, rather than by value.

Bohemian
  • 412,405
  • 93
  • 575
  • 722