1

I have two List2. I stores items in one list and in 2nd list I am storing int numbers which I consider as indexes.

I want remove items from items list with all indexes.

ArrayList<String> items = new ArrayList<String>();

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

items.add("a");
items.add("b"); // should be removed
items.add("c"); 
items.add("d"); // should be removed
items.add("e");
items.add("f"); // should be removed 
items.add("g");
items.add("h");


indexes.add(1);
indexes.add(3);
indexes.add(5);


Output : items : [a,c,e,g,h]
James Z
  • 12,209
  • 10
  • 24
  • 44
Maqsood Hakro
  • 27
  • 1
  • 8

4 Answers4

3

You should add in the end:

  Collections.reverse(indexes); 
    for(Integer index : indexes){
        items.remove((int)index);
    }
  1. Reverse list with indexes, because when you delete from 1 to n next letter change index numbers and when you want delete index "3" you really delete index "4".
  2. Loop thru the indexes you want to delete.
  3. Cast Integer to int - remove(int index).

Done.

0

Solution using java stream API,

IntStream.range(0, items.size()).filter(i -> !indexes.contains(i)).mapToObj(items::get)
                .collect(Collectors.toList())
Shaunak Patel
  • 1,581
  • 11
  • 14
0
 public static void filter(List<String> list, List<Integer> indexesToRemove){
        Collections.reverse(indexesToRemove);
        for (Integer indexToRemove : indexesToRemove) {
            list.remove((int)indexToRemove);
        }

    }
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<String>();

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

        items.add("a");
        items.add("b"); // should be removed
        items.add("c");
        items.add("d"); // should be removed
        items.add("e");
        items.add("f"); // should be removed
        items.add("g");
        items.add("h");


        indexes.add(1);
        indexes.add(3);
        indexes.add(5);

        filter(items, indexes);
        System.out.println(items);
    }

Here You go. Remove from arrays starts of biggest index :)

Adrian
  • 84
  • 2
  • 6
0

For anyone that was stuck and landed on this page, but your indices were not a List of indices, but an array of indices. This page was helpful but I tweaked the answers a little bit, and it worked. The code below

 Arrays.sort(itemIndices, Collections.reverseOrder());
        for (int i : itemIndices) {
            uriCache.add(mediaUris.remove(i));
        }

Note: ItemIndices represents the indices of the positions in the list, you want to remove. uriCache is not necessary, i used it in my code to store a list of the removed items (which were URIs, by the way). mediaUris is the list you would like to remove those items with indices specified by the array itemIndices

Noah
  • 567
  • 5
  • 21