java 如何根据对象的属性将list中的对象删除
时间: 2023-09-24 18:14:09 浏览: 38
可以通过遍历list中的对象,判断对象的属性是否符合要求,如果符合就将该对象从list中删除。示例代码如下:
```java
public static <T> void removeByProperty(List<T> list, String propertyName, Object propertyValue) {
Iterator<T> iterator = list.iterator();
while (iterator.hasNext()) {
T obj = iterator.next();
try {
Field field = obj.getClass().getDeclaredField(propertyName);
field.setAccessible(true);
Object value = field.get(obj);
if (value != null && value.equals(propertyValue)) {
iterator.remove();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`propertyName`为对象的属性名,`propertyValue`为属性对应的值。使用时,调用该方法即可实现根据属性删除对象:
```java
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("张三", 18));
studentList.add(new Student("李四", 20));
removeByProperty(studentList, "name", "张三");
```
上述代码中,删除了符合`name`为“张三”的对象。