Skip to content
Advertisement

Remove elements from a List at a specific index

I am trying to program a method that deletes the first, second and third element of every group of 4 elements. It seems not working at all. Could anyone please help?

public static void reduziereKommentare(List<String> zeilen) {
        if (!zeilen.isEmpty()) {
            if (zeilen.size() % 4 != 0) {
                throw new RuntimeException("Illegal size " + zeilen.size() + " of list, must be divisible by 4.");
            }
            for (int i = 1; i <= zeilen.size() % 4; i++) {
                zeilen.remove(i);
                zeilen.remove(i + 1);
                zeilen.remove(i + 2);
            }
        }
        System.out.println(zeilen);
    }

Advertisement

Answer

My take…does not require the size precondition check but you may want to still catch that if it represents an error of broader scope than this method.

Given this test code…

    // Test code
    List<String> myList = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        myList.add(String.valueOf(i));
    }
    

the ‘zeilen’ loop can be implemented as …

    // "before" diagnostics
    System.out.println(zeilen);

    // The 'zeilen' loop
    for (int i = 0, limit = zeilen.size(); i < limit; i++) {
        if ((i+1) % 4 > 0) zeilen.remove(i/4);
    }

    // "after" diagnostics
    System.out.println(zeilen);

and produces

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[3, 7, 11, 15, 19]

Works with any length list leaving every ‘4th’ element in list.

A few more test cases :

Given                   Results in
[]                      []
[0,1]                   []
[0,1,2,3]               [3]
[0,1,2,3,4]             [3]
[0,1,2,3,4,5,6,7]       [3,7]
[0,1,2,3,4,5,6,7,8]     [3,7]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement