查找list集合中存储的对象的属性值的方法
package com.lld.list.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.lld.model.TestModel;
public class ListUtils {
public static<T> List<T> containsByProperty(List<T> list,String Property,Object value,Class<T> clazz){
List<T> list1 = new ArrayList<>();
try {
Field field = clazz.getDeclaredField(Property);
field.setAccessible(true);
for (T t : list) {
Object obj = field.get(t);
if (value.equals(obj)) {
list1.add(t);
}
}
} catch (Exception e) {
}
return list1;
}
public static void main(String[] args) {
List<TestModel> list = new ArrayList<>();
list.add(new TestModel("张三","16"));
list.add(new TestModel("李四","17"));
list.add(new TestModel("王五","18"));
List<TestModel> containsByProperty = containsByProperty(list, "name", "张三", TestModel.class);
for (TestModel testModel : containsByProperty) {
System.out.println(testModel);
}
}
}
package com.lld.model;
public class TestModel {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public TestModel(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {
return "TestModel [name=" + name + ", value=" + value + "]";
}
}