Java根据类属性值从一个集合中找到和该属性相等的对象

方法

使用common-utils包提供的CollectionUtilsBeanPropertyValueEqualsPredicate

比如找id属性值为9587的用户

Object obj = CollectionUtils.find(UserList.get(), 
new BeanPropertyValueEqualsPredicate("id", "9587"));
if(obj == null){
    log.info("not found");
}else{
    //do your thing
}

find方法实现的大概思路

public static <T> T findElementByPropertyValue(List<T> list, String propertyName, Object value) throws Exception {
    if(list == null || list.isEmpty()) {
        return null;
    }
    PropertyDescriptor pd = new PropertyDescriptor(propertyName, list.get(0).getClass());
    for (T t : list) {
        Object obj = pd.getReadMethod().invoke(t);
        if(StringUtils.equals(String.valueOf(value), String.valueOf(obj))) {
            return t;
        }
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/u012557814/article/details/80868998