遍历List删除元素
方法一:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add(null);
list.add("5"); for(int i=0; i<list.size(); i++){
list.remove(i);
i--;
}
System.out.println(list.size());
方法二:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add(null);
list.add("5");
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
String tmp = (String)iterator.next();
iterator.remove();
}
System.out.println(list.size());
遍历Map删除元素
方法一:
Map<String,String> map = new HashMap<>();
map.put("1","aaa");
map.put("2","bbb");
map.put("3","ccc");
map.put("4","ddd");
map.put("5","eee"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
it.remove();
}
System.out.println(map.size());
方法二:
Map<String,String> map = new HashMap<>();
map.put("1","aaa");
map.put("2","bbb");
map.put("3","ccc");
map.put("4","ddd");
map.put("5","eee"); for (Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
it.remove();
}
System.out.println(map.size());