赞
踩
遍历List,动态删除元素的四种方法
公共代码块如下:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Baidu");
list.add("Alibaba");
list.add("Tencent");
list.add("Google");
list.add("Gucci");
System.out.println(list);
// test1(list);
// test2(list);
// test3(list);
// test4(list);
}
public static void test1(List<String> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).startsWith("G")) {
list.remove(i);
}
}
System.out.println(list);
}
public static void test2(List<String> list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.startsWith("G")) {
iterator.remove();
}
}
System.out.println(list);
}
public static void test3(List<String> list) {
list = list.stream().filter(s -> !s.startsWith("G")).collect(Collectors.toList());
System.out.println(list);
}
public static void test4(List<String> list){
list.removeIf(s -> s.startsWith("G"));
System.out.println(list);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。