" />

欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java8在遍歷集合時刪除元素問題解決

 更新時間:2023年06月16日 08:56:30   作者:Olrooki  
本文主要介紹了Java8在遍歷集合時刪除元素問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

在最近工作中遇到了需要在遍歷List時刪除掉某些元素的情況,這時不能再使用之前一直常用的fori或者增強(qiáng)for循環(huán),會導(dǎo)致ConcurrentModificationException 異常。這時候可以使用迭代器Iterator或者Java8的removeIf解決問題,這里簡單說明下兩種方法的簡單使用及一些注意普通for循環(huán)直接處理該問題所出現(xiàn)的情況。

簡單需求如下:

/**
 * 將list中和字符串"1"相同的元素去除并輸出去除后的list
 */
List<String> list = new ArrayList<>(Arrays.asList("1","1","2","3","4","5"));

使用fori循環(huán)刪除

for (int i = 0; i < list.size(); i++) {
    if ("1".equals(list.get(i))) {
        list.remove(i);
    }
}

運(yùn)行結(jié)果為:[1, 2, 3, 4, 5]

這里可以看到有一個元素 "1" 并沒有被刪除

如果使用增強(qiáng)for循環(huán)刪除

for (String a : list) {
    if ("1".equals(a)) {
        list.remove(a);
    }
}

運(yùn)行結(jié)果為:

Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)                
        at java.util.ArrayList$Itr.next(ArrayList.java:851)
        at com.lingxiao.cloudlingxiaodigitalproject9107.service.impl.Demo2.main(Demo2.java:27)

通過迭代器實(shí)現(xiàn)

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
? ? if ("1".equals(iterator.next())) {
? ? ? ? iterator.remove();
? ? }
}
System.out.println(list);

運(yùn)行結(jié)果為:[2, 3, 4, 5]

這里:iterator.hasNext()用來遍歷,iterator.next()為元素的值,通過iterator.remove()方法去除元素

通過removeIf方法實(shí)現(xiàn)

list.removeIf(a -> "1".equals(a));

這里的lambda表達(dá)式可以簡寫

list.removeIf("1"::equals);

這里使用 “::” 簡化了lambda表達(dá)式

運(yùn)行結(jié)果依然為:[2, 3, 4, 5]

當(dāng)我們在遍歷集合時需要刪除元素,需要使用迭代器或者removeIf方法

到此這篇關(guān)于Java8在遍歷集合時刪除元素問題解決的文章就介紹到這了,更多相關(guān)Java8 遍歷刪除元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論