【问题标题】:Removing entries from a list?从列表中删除条目?
【发布时间】:2011-12-20 20:46:55
【问题描述】:

假设您有一个支持删除功能的 ArrayList - 它删除条目并将所有内容移到右侧的左侧。

如果我想在特定条件下从列表中删除某些东西,我可能会这样做:

for (int i = 0; i < list.size(); i++) {
  if (condition) {
    list.remove(i);
    i--;
  }
}

但这很丑陋,感觉很hackish。你可以用迭代器做同样的事情,但你不应该在使用迭代器时改变列表。

那么不丑的解决方案是什么?

【问题讨论】:

标签: java list


【解决方案1】:

迭代器实际上可以用于此目的,这也是Oracle documentation 所推荐的。

这是上面的遍历集合 - 迭代器下的链接提供的代码:

static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

最重要的是,在上面的例子中,他们说:

请注意,Iterator.remove 是修改集合的唯一安全方法 在迭代期间;如果底层的行为是未指定的 在迭代中以任何其他方式修改集合 进展。

【讨论】:

    【解决方案2】:

    我只使用了一个循环,但改为递减计数器

    for(int i=list.size()-1; i>=0; --i) {
      if(condition) {
         list.remove(i);
      }
    }
    

    【讨论】:

    • 不,这意味着您不能在使用迭代器遍历集合时安全地修改集合。我没有使用迭代器,我使用的是循环。
    • 哎呀,你没有使用迭代器,我的错。
    【解决方案3】:

    试试这个

    Iterator itr = list.iterator(); 
    while(itr.hasNext()) {
    if(condition)
        itr.remove();
    } 
    

    希望这个 shud 工作.. 尝试否则会建议另一个

    我还有一个给你,它也检查条件......

    int count=0;
    Iterator itr = list.iterator(); 
    while(itr.next()) {
    count++;
    if(condition=count)
        itr.remove();
    } 
    

    【讨论】:

      【解决方案4】:

      Guava 为 Java 提供了一些函数式风味。 在您的情况下,它将是:

       FluentIterable.from(your_iterable).filter(new Predicate<Type_contained_in_your_iterable>()                    {
                  @Override
                  public boolean apply(@Nullable Type_contained_in_your_iterable input) {
                      return {condition};
                  }
              });
      

      请注意,您的谓词只会返回满足您条件的可迭代元素。 这样就清楚多了。是不是。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-27
        • 2020-11-17
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多