Deleting objects from an ArrayList in Java

前端 未结 13 1846
轮回少年
轮回少年 2020-12-15 03:14

I need to delete some objects from an ArrayList if they meet a condition and I\'m wondering which way could be more efficient.

Here\'s the situation: I

相关标签:
13条回答
  • 2020-12-15 03:59

    I have found an alternative faster solution:

      int j = 0;
      for (Iterator i = list.listIterator(); i.hasNext(); ) {
        j++;
    
        if (campo.getNome().equals(key)) {
           i.remove();
           i = list.listIterator(j);
        }
      }
    
    0 讨论(0)
  • 2020-12-15 04:02

    Most performant would, I guess, be using the listIterator method and do a reverse iteration:

    for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();){
        if (weWantToDelete(iter.previous()))  iter.remove();
    }
    

    Edit: Much later, one might also want to add the Java 8 way of removing elements from a list (or any collection!) using a lambda or method reference. An in-place filter for collections, if you like:

    list.removeIf(e -> e.isBad() && e.shouldGoAway());
    

    This is probably the best way to clean up a collection. Since it uses internal iteration, the collection implementation could take shortcuts to make it as fast as possible (for ArrayLists, it could minimize the amount of copying needed).

    0 讨论(0)
  • 2020-12-15 04:02

    With an iterator you can handle always the element which comes to order, not a specified index. So, you should not be troubled with the above matter.

    Iterator itr = list.iterator();
    String strElement = "";
    while(itr.hasNext()){
    
      strElement = (String)itr.next();
      if(strElement.equals("2"))
      {
        itr.remove();
      }
    
    0 讨论(0)
  • 2020-12-15 04:03

    Maybe Iterator’s remove() method? The JDK’s default collection classes should all creator iterators that support this method.

    0 讨论(0)
  • 2020-12-15 04:06

    Unless you're positive that the issue you're facing is indeed a bottleneck, I would go for the readable

    public ArrayList filterThings() {
    
        ArrayList pileOfThings;
        ArrayList filteredPileOfThings = new ArrayList();
    
        for (Thing thingy : pileOfThings) {
            if (thingy.property != 1) {
                filteredPileOfThings.add(thingy);
            }            
        }
        return filteredPileOfThings;
    }
    
    0 讨论(0)
  • 2020-12-15 04:07

    First, I'd make sure that this really is a performance bottleneck, otherwise I'd go with the solution that is cleanest and most expressive.

    If it IS a performance bottleneck, just try the different strategies and see what's the quickest. My bet is on creating a new ArrayList and puting the desired objects in that one, discarding the old ArrayList.

    0 讨论(0)
提交回复
热议问题