首页 > 解决方案 > Remove multiple elements with multiple indexes from arraylist in java

问题描述

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]

标签: javaarraysstringarraylist

解决方案


你应该在最后添加:

  Collections.reverse(indexes); 
    for(Integer index : indexes){
        items.remove((int)index);
    }
  1. 带索引的反向列表,因为当您从 1 到 n 删除下一个字母更改索引号时,当您想要删除索引“3”时,您实际上删除了索引“4”。
  2. 循环遍历要删除的索引。
  3. 将整数转换为 int - remove(int index)

完毕。


推荐阅读