java iterator


遍历删除集合中的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {

List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

// java8 之前删除集合元素
Iterator<Integer> iterator = nums.iterator();
while (iterator.hasNext()) {
int num = iterator.next();
if (num % 2 == 0) {
iterator.remove();
}
}

System.out.println(nums);
}

java8 应该使用stream。

1
nums = nums.stream().filter(num -> num % 2 == 0).collect(toList());


  java
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×