方法一:过滤器 list.removeIf() 实现
public List<User> selectUserList(User user){
List<User> userList= userMapper.selectUserList();
return userList.removeIf((User u)->!u.getSex().equals(user.getSex()));
}
具体如下:
使用
list.removeIf()
方法,removeIf()
的入参是一个过滤条件,用来判断需要移除的元素是否满足条件。
原理:方法中设置了一个removeSet
,把满足条件的元素索引坐标都放入removeSet
,然后统一对removeSet
中的索引进行移除示例:将姓张的名字移除掉
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五", "赵六"));
nameList.add("张七");
nameList.add("张八");
nameList.removeIf(o->o.startsWith("张"));
System.out.println(nameList);
方法二:for 循环 int i=list.size()-1 (倒序遍历元素然后删除)
正序删除元素会移位,那我们转变思维倒序遍历
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五", "赵六"));
nameList.add("张七");
nameList.add("张八");
for (int i = nameList.size() - 1; i >= 0; i--) {
String name = nameList.get(i);
System.out.println("当前遍历对象===" + name);
if (name.startsWith("张")) {
nameList.remove(i);
}
}
System.out.println(nameList);
方法三:foreach 循环
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五", "赵六"));
nameList.add("张七");
nameList.add("张八");
List<String> removeList = new ArrayList<>();
for (String name : nameList) {
if (name.startsWith("张")) {
removeList.add(name);
}
}
nameList.removeAll(removeList);
System.out.println(nameList);