Java Arraylist按索引删除多个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29656071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:41:01  来源:igfitidea点击:

Java Arraylist remove multiple element by index

javaandroidarrayliststop-words

提问by Lita

Here is my code:

这是我的代码:

for (int i = 0; i < myarraylist.size(); i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).equals(myarraylist.get(i))) {
                myarraylist.remove(i);
                id.remove(i);
                i--; // to look at the same index again!
            }
        }
    }

I have problem.. after element removed, all index always changed, the loop above so messy.

我有问题..删除元素后,所有索引总是改变,上面的循环太乱了。

To illustrate: I have 54 data, but loop above become messy after element removed.. so only 50 data that checked.

举例说明:我有 54 个数据,但是在删除元素后上面的循环变得混乱..所以只有 50 个数据被检查。

Is there another way or fix my code to remove multiple element by index?? element index is so important to me, to remove another arraylist that have the same index.

有没有另一种方法或修复我的代码以按索引删除多个元素?元素索引对我来说非常重要,删除另一个具有相同索引的数组列表。

回答by Steve Kuo

Use Iterator.remove()to remove elements while iterating.

用于Iterator.remove()在迭代时删除元素。

for (Iterator<String> iter = myarraylist.iterator(); iter.hasNext(); ) {
  String element = iter.next();
  if (element meets some criteria) {
    iter.remove();
  }
}

Or use Google Guava's filterwhich returns a filtered view and leaves the original list unchanged.

或者使用谷歌番石榴的过滤器,它返回一个过滤视图并保持原始列表不变。

Iterable<String> filtered = Iterables.filter(myarraylist, new Predicate<String>() {
  public boolean apply(String element) {
    return true of false based on criteria
  }
});

回答by Ungeheuer

One thing you need to keep in mind is that when you use ArrayListsthat they are meant to be versatile, moreso than Arrays. You can shorten an array by removing an entire index, add an index to it, and do wonderfulness with ArrayLists.

您需要记住的一件事是,当您使用ArrayLists它们时,它们意味着多功能,而不仅仅是Arrays. 您可以通过删除整个索引来缩短数组,为其添加索引,并使用ArrayLists.

This is a common problem with people who do not realize, or remember, that when you remove a value, the ArrayListindexes (or whatever the correct plural is) readjust and the ArrayListshortens.

对于那些没有意识到或记住当您删除一个值时,ArrayList索引(或任何正确的复数形式)会重新调整和ArrayList缩短的人来说,这是一个常见问题。

When attempting to remove elements from an ArrayList, you should always start at the end of the ArrayList.

尝试从 中删除元素时ArrayList,应始终从 的末尾开始ArrayList

for(int x = arrayList.size() - 1; x > 0; x--)
{
    arrayList.remove(x);
}

This should provide you with the function that you are looking for. Take a look at the ArrayList APIfor other methods that may help you.

这应该为您提供您正在寻找的功能。查看ArrayList API以了解其他可能对您有帮助的方法。

回答by Stranger in the Q

looks like as you want to remove one collection from another.. You should use java.util.Collection#removeAll method instead

看起来就像你想从另一个集合中删除一个集合..你应该改用 java.util.Collection#removeAll 方法

回答by Panther

while iterating list and you are removing the object use iterator.

在迭代列表并且您正在删除对象时使用迭代器。

Iterator myListItr = myarraylist.iterator();
//Iterate on list 
    while(myListItr .hasNext()) {
    //if stop words is list of string then contains will work as it is. If its your custom object then override equals method.
        if(stopwords.contains( myListItr.next())){
    myListItr.remove();
}
}

回答by bonnyz

Not sure about why you want to do this by index, but you can try this (untested):

不确定为什么要按索引执行此操作,但您可以尝试此操作(未经测试):

int dynamicSize = myarraylist.size();
for (int i = 0; i < dynamicSize; i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).equals(myarraylist.get(i))) {
                myarraylist.remove(i);
                id.remove(i);
                i--; // to look at the same index again!
                dynamicSize--;
            }
        }
    }

回答by Yash

Using ListIterator

使用ListIterator

ArrayList<String> list = new ArrayList<String>();
      // List : ["java", ".net", "javascript", "html", "css", "selenium", "image", "Spring"]

    ArrayList<Integer> indexes = new ArrayList<Integer>();
                                      // indexes : [5, 3, 2, 5, 0]
    // Sort the Indexes in Order to remove from back words. and make Unique
    TreeSet<Integer> uniqueSorted = new TreeSet<Integer>();
        uniqueSorted.addAll(indexes);

    // To remove all elements from the ArrayList and make its size = 0  
        indexes.clear(); 
        indexes.addAll(uniqueSorted);

    // Iterate form back, so that if size decreases also no problem.
    ListIterator<Integer> li = indexes.listIterator(indexes.size());

   // we can traverse a List in both the directions (forward and Backward).
        while(li.hasPrevious()) {
            int position = li.previous();
            list.remove(position);
        }

回答by Vinayak Mestri

Ok this is very good problem to solve. Lets start with an exmaple

好的,这是一个很好的问题来解决。让我们从一个例子开始

We have data = [5,2,7,3,9,34,63,23,85,23,94,7]

我们有 data = [5,2,7,3,9,34,63,23,85,23,94,7]

indexes to remove

要删除的索引

int index[] = [5,2,7,9]

Note: As you remove single item from array other elements get shifted by 1.

注意:当您从数组中删除单个项目时,其他元素会移动 1。

If we use ArrayList to remove elements of indexes then first you need to sort the indexes in descending.

如果我们使用 ArrayList 删除索引的元素,那么首先您需要对索引进行降序排序。

i.e indexes = [9,7,5,2] then remove the element from index

即索引 = [9,7,5,2] 然后从索引中删除元素

ArrayList<Integer> data = Arrays.asList(new Integer[] {5,2,7,3,9,34,63,23,85,23,94,7});

for(int i=0;i<index.length;i++){
    data.remove(index[i]);
    }