1.removeIf()
java
List<String> list = new ArrayList<>();
list.add("zs");
list.add(null);
list.add("ls");
list.add(null);
list.add("");
list.forEach(o -> System.out.println("删除前:" + o));
list.removeIf(Objects::isNull);
list.removeIf(o -> Objects.equals(o,"")); //同理也可以是其他值
list.forEach(o -> System.out.println("删除后:" + o));
2.lambda
java
List<String> list = new ArrayList<>();
list.add("zs");
list.add(null);
list.add("ls");
list.add(null);
list.forEach(o -> System.out.println("删除前:" + o));
List<String> collect = list.stream().filter(o -> o != null && !Objects.equals(o,"")).collect(Collectors.toList());
collect.forEach(o -> System.out.println("删除后:" + o));
3.HuTool工具
java
List<String> list = new ArrayList<>();
list.add("zs");
list.add(null);
list.add("ls");
list.add(null);
list.forEach(o -> System.out.println("删除前:" + o));
CollectionUtil.removeNull(list);//只能删除null
CollectionUtil.removeEmpty(list);//能删除null和"" 删不了" "
list.forEach(o -> System.out.println("删除后:" + o));
HuTool Maven 依赖
xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
官方文档 https://doc.hutool.cn/pages/index/
4.CollectionUtils
java
List<String> list = new ArrayList<>();
list.add("zs");
list.add(null);
list.add("ls");
list.add(null);
list.add("");
list.forEach(o -> System.out.println("删除前:" + o));
CollectionUtils.filter(list,o -> !Objects.equals("",o) && o != null);
list.forEach(o -> System.out.println("删除后:" + o));
Maven 依赖
xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
5.迭代器
java
List<String> list = new ArrayList<>();
list.add("zs");
list.add(null);
list.add("ls");
list.add(null);
list.add("");
list.forEach(o -> System.out.println("删除前:" + o));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next == null || (next != null && next.equals(""))) {
iterator.remove();
}
}
list.forEach(o -> System.out.println("删除后:" + o));