Java中删除List中元素的方法大全
下文笔者讲述list中删除元素的方法大全,如下所示
List删除元素的实现思路
方式1: 借助removeIf方法删除list中指定元素 方式2: 借助迭代器中remove方法删除指定元素 方式3: 倒序遍历的方式删除元素 方式4: for循环删除 方式5: 增强for循环删除 方式6: iterator遍历删除例:
jdk 1.8以后removeif方法删除元素
List<String> strList2 = new ArrayList<>(); strList2.add("java265.com-1"); strList2.add("java265.com-2"); strList2.add("java265.com-3"); strList2.add("java265.com-4"); strList2.removeIf(s->(s.equals("java265.com-3"))); System.out.println("参数"+strList2);
(使用迭代器中remove方法)
在使用迭代器遍历时
可使用迭代器的remove方法
因为Iterator的remove方法中
public void testDel() {
List<Integer> list = Lists.newArrayList();
list.add(1);
list.add(2);
list.add(2);
list.add(2);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
if (integer == 2)
iterator.remove();
}
}
(倒序遍历删除)
public void testDel() {
List<Integer> list = Lists.newArrayList();
list.add(1);
list.add(2);
list.add(2);
list.add(2);
list.add(2);
for(int i=list.size()-1;i>=0;i--){
if(list.get(i)==2){
list.remove(i);
}
}
}
for循环遍历list,然后删除
for(int i=0;i<list.size();i++){
if(list.get(i).equals("del"))
list.remove(i);
}
//此种删除方式会导致相应的异常发生
//list大小发生变化,而你的索引也在变化
//会导致你在遍历的时候漏掉某些元素
//如当你删除第1个元素后,继续根据索引访问第2个元素时
//因为删除的关系后面的元素都往前移动了一位
//所以实际访问的是第3个元素
//因此,这种方式可以用在删除特定的一个元素时使用,但不适合循环删除多个元素时使用
增强for循环
for(String x:list){
if(x.equals("del"))
list.remove(x);
}
iterator遍历
Iterator<String> it = list.iterator();
while(it.hasNext()){
String x = it.next();
if(x.equals("del")){
it.remove();
}
}
如果循环删除list中特定一个元素 可使用以上方式中的任意一种 但在使用中要注意上面分析的各个问题。 如果循环删除list中多个元素 应该使用迭代器iterator方式
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


