java中 过滤list的几种方式
方式一:使用java 8语法:stream+反射
Liststudent3List=new ArrayList<>();
Student3 student3=new Student3();
student3.setId(1);
student3.setName("攀博士");
student3.setStudyNo("228332");
student3.setAge(20);
student3List.add(student3);
student3=new Student3();
student3.setId(2);
student3.setName("黄鹤");
student3.setStudyNo("228333");
student3.setAge(22);
student3List.add(student3);
student3=new Student3();
student3.setId(3);
student3.setName("阿猛");
student3.setStudyNo("228334");
student3.setAge(25);
student3List.add(student3);
List newStudents=student3List.stream().filter(new Predicate() {
@Override
public boolean test(Student3 student) {
return student.getName().equals("黄鹤");
}
}).collect(Collectors.toList());
int size=newStudents.size();
抽取为通用的过滤方法:
List newStudents = filterList(student3List);
public static List filterList(List student3List) {
return (List) student3List.stream().filter(new Predicate() {
@Override
public boolean test(Object student) {
return ReflectHWUtils.getObjectValue(student,"name").equals("阿猛");
}
}).collect(Collectors.toList());
}
进一步抽取:
List newStudents=filterList(student3List,"name","阿猛");
public static List filterList(List student3List,String column,String columnValue) {
return (List) student3List.stream().filter(new Predicate() {
@Override
public boolean test(Object student) {
return ReflectHWUtils.getObjectValue(student,column).equals(columnValue);
}
}).collect(Collectors.toList());
}
方式二:遍历+反射
List newStudents = getObjFromList(student3List,"name","攀博士");
/***
* 获取指定值的对象
*
* @param list
* @param property
* @param valueCompare
* @return
*/
public static List getObjFromList(List list, String property,
Object valueCompare) {
if (ValueWidget.isNullOrEmpty(list)) {
return null;
}
List filterList = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
Field keyf = null;
keyf = ReflectHWUtils.getSpecifiedField(obj.getClass(), property);
if (null == keyf) {
continue;
}
keyf.setAccessible(true);
try {
Object value22 = keyf.get(obj);
if (ReflectHWUtils. isSameBySimpleTypes(value22, valueCompare)) {
filterList.add(obj);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return filterList;
}
反射类 ReflectHWUtils 见
https://github.com/liuyu520/io0007
的com.common.util.ReflectHWUtils
方式三:使用guava
Iterablestudent3Iterator= Iterables.filter(student3List,new com.google.common.base.Predicate(){
@Override
public boolean apply(Student3 student3) {
return student3.getName().equals("攀博士");
}
});