删除元素
第一种:迭代器
Iterator<Project> it = projectList.iterator(); while(it.hasNext()){ Project p=it.next(); if (!allProjectMap.containsKey(p.getId())){ it.remove(); }; }
第三种
使用remove,但是要小心list的size,因为list删除一个元素后面的元素就会前移,所以要倒着删除
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); for (int i = list.size() - 1; i >= 0; i--) { String str = list.get(i); if ("aa".equals(str)) { list.remove(str); } } System.out.println(list.size()); } }
第三种:使用CopyOnWriteArrayList
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<String>(list); for (String str : cowList) { if ("aa".equals(str)) { cowList.remove(str); } } System.out.println(cowList.size()); } }
第四种:双重for循环删除
for (int i = projectList.size() - 1; i >= 0; i--) { for (int j = projectList.size() - 1; j >= 0; j--) { if (projectList.get(i).getId().equals(projectList.get(j).getId())) { if (projectList.get(i).getHigh() != null && projectList.get(j).getHigh() != null) { if (projectList.get(i).getHigh() > projectList.get(j).getHigh()) { projectList.remove(j); i-=1; } } } } }
list如何删除空元素
list.removeAll(Collections.singleton(null)); list.removeIf(Objects::isNull); List<String> newList = list.stream().filter(Objects::nonNull).collect(Collectors.toList());