删除与值不匹配的arraylist中的值

时间:2016-03-03 14:33:35

标签: java arrays arraylist

我在删除与给定值不匹配的值时遇到了一些麻烦。目前,我正在将值复制到新列表并尝试清除原始列表 - 但这效率很低。

这是我的代码:

int size = list.size();
ArrayList<String> newList;
int count = 0;
newList = new ArrayList<>();
for (int i=0; i<list.size(); i++){
    if(list.get(i).getForename().equals(forename)){
        newList.add(i, list);
    }
}
list.clear();

有没有办法可以删除arraylist中的项目,如果它与名称不匹配?

修改 它工作但我可能需要一个副本,就像我从下拉列表中选择另一个名称,它将指的是旧的

由于

5 个答案:

答案 0 :(得分:3)

首先想到的是迭代列表,一旦找到与该值不匹配的项目,就将其删除。但它会创建一个并发修改异常,因为您在尝试删除其中的元素时迭代列表。 另一个仍然无效的方法是迭代列表,跟踪要删除的索引,并在迭代列表后删除它们。

ArrayList<Integer> indexList = new ArrayList<Integer>();
for(int i = 0; i<list.size(); i++){
   if(!list.get(i).getForename().equals(forename)){
    indexList.add(i);
}
for(Integer index : indexList){
  list.remove(index);
}
indexList.clear();

请注意,这也不是很有效,但也许您正在寻找从同一列表中删除的方法。

答案 1 :(得分:1)

一个简单的解决方案是

while (list.contains(value)) {
            list.remove(list.indexOf(value));
        }

答案 2 :(得分:0)

根据您的需要,您可能希望改用流(似乎是您真正想要的,因为您似乎并不想删除列表中的元素):

newList = list.stream()
                .filter(e -> getForename().equals(forename))
                .collect(Collectors.toList());

或执行您可能想要执行的操作:

list.stream()
        .filter(e -> getForename().equals(forename))
        .forEach(person -> doStuff(person));

另一种方法是使用迭代器来避免在迭代期间与修改冲突:

ListIterator iterator = list.listIterator();
while(iterator.hasNext()){
    if(!iterator.getNext().getForename().equals(forename))
         iterator.remove();
}

编辑:由于OP不能使用lambdas和流(因为Java版本),所以第二个流(forEach)几乎会发生这种情况。我没有使用正确的接口,因为OP也不能这样做。与流的区别在于,它们也可能将其拆分为多个线程,因此速度更快(特别是在多核处理器和大型列表中):

interface Consumer<T>{  //this is normally given by the JAVA 8 API (which has one more default method)
    void accept(T t);
}

Consumer<YourObject> doIt = new Consumer<YourObject>(){ //This is what the lambda expression actually does
    @Override
    public void accept(YourObject e) {
        doStuff(e);
    }
};


for(YourObject element : list){ //since JAVA 1.5. Alternativ your old for-loop with element=list.get(i);
    if(!element.getForename().equals(forename)) //the filter written in easy
        continue;
    doIt.accept(element); //You could also use a method or expressions instead in this context.
    //doStuff(element);   //What actually the upper stream does.
}

你可能想看一下oracle教程(本章),感受一下这个设计是否合适https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html(我有一种强烈的感觉,你可能想要使用它)。

答案 3 :(得分:0)

假设您的List包含String对象,以下内容应该是您要查找的内容:

for (Iterator<String> it = list.iterator(); it.hasNext()){
    String foreName = it.next();
    if(forName != null && foreName.equals(forename)){
        it.remove();
    }
}

答案 4 :(得分:-1)

for (int i=0; i<list.size();){
    if(!list.get(i).getForename().equals(forename)){
        list.remove(i);
    }
    else {
        i++;
    }
}
相关问题