java - 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]
解决方案
你应该在最后添加:
Collections.reverse(indexes);
for(Integer index : indexes){
items.remove((int)index);
}
- 带索引的反向列表,因为当您从 1 到 n 删除下一个字母更改索引号时,当您想要删除索引“3”时,您实际上删除了索引“4”。
- 循环遍历要删除的索引。
- 将整数转换为 int - remove(int index)。
完毕。
推荐阅读
- c++ - 为什么要对共享库本身中定义的符号使用全局偏移表?
- javascript - 使用扩展和内容脚本注入 Chrome 的脚本不会首先执行
- java - SQLLoader 704 通过 JAVA 加载时发生内部错误
- mercurial - Mercurial HG - 如何从未提交的文件中清除 repo 并保留在当前的变更集中?
- javascript - 如何解决参数内的 URL 中有撇号
- kivy - 如何在 kivy 项目中使用或添加 android library(aar) 文件?
- c# - microsoft botframework-v4 的兼容性
- c# - 尝试使用从 URL 接收的 3 个参数制作控制器
- javascript - 匹配 ID 和检查属性的数组过滤方法是否存在
- linux - 从 32 位用户空间访问 36 位物理地址