簡體   English   中英

從列表中刪除條目?

[英]Removing entries from a list?

假設您擁有一個支持remove函數的ArrayList -刪除該條目並將所有內容向右移到左邊。

如果要在特定條件下從列表中刪除內容,可以執行以下操作:

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

但這是丑陋的,讓人覺得有點黑。 您可以使用Iterator進行相同的操作,但在使用Iterator時不應更改列表。

那么什么是非丑陋的解決方案?

實際上,迭代器可用於此目的,這是Oracle文檔建議的。

這是上面的鏈接在遍歷集合-迭代器下提供的代碼:

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

最重要的是,在該示例之上,他們說:

注意, Iterator.remove是在迭代過程中修改集合的唯一安全方法。 如果在進行迭代時以任何其他方式修改了基礎集合,則行為未指定。

我只是使用循環,而是減少計數器

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

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};
            }
        });

請注意,謂詞只會返回滿足您條件的可迭代元素。 這樣更加清晰。 是不是

嘗試這個

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

希望如此工作能順利進行..否則會建議另一個

我還有另一個要檢查的狀況。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM