首页 > 代码库 > 遍历List、Map删除元素

遍历List、Map删除元素

遍历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删除元素

方法一:

 1 Map<String,String> map = new HashMap<>(); 2 map.put("1","aaa"); 3 map.put("2","bbb"); 4 map.put("3","ccc"); 5 map.put("4","ddd"); 6 map.put("5","eee"); 7  8 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); 9 while (it.hasNext()) {10     Map.Entry<String, String> entry = it.next();11     it.remove();12 }13 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());

 

遍历List、Map删除元素