循环list从list中移除数据

时间:2021-10-16 00:06:01
package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author 
 * @create 2018-03-14 17:14
 */
public class HelloWord {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(5);
        list.add(9);
        list.add(10);

        Iterator<Integer> integerIterator = list.iterator();
        while(integerIterator.hasNext()) {
            int i = integerIterator.next();
            if(i == 1) {
                integerIterator.remove();
            }
        }

        // 注意重新获取迭代器
        Iterator<Integer> integerIterator1 = list.iterator();
        while(integerIterator1.hasNext()) {
            int i = integerIterator1.next();
            if(i == 10) {
                integerIterator1.remove();
            }

        }
        System.out.println(Arrays.toString(list.toArray()));
    }
}