java 属性 list_java将对象列表中的某个属性转换成List或Map

import org.apache.commons.beanutils.PropertyUtilsBean;

import java.lang.reflect.InvocationTargetException;

import java.util.HashMap;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

/**

* Created by AJAX on 2017/1/3.

*/

public class PropertiesUtils {

/**

* 根据对象列表和对象的某个属性返回属性的List集合

*

* @param objList

*            对象列表

* @param propertyName

*            要操作的属性名称

* @return

 
 

*  指定属性的List集合;

*  如果objList为null或者size等于0抛出 IllegalArgumentException异常;

*  如果propertyName为null抛出 IllegalArgumentException异常

*

* @throws NoSuchMethodException

* @throws InvocationTargetException

*/

public static List getPropertyList(List objList, String propertyName) throws IllegalAccessException,

InvocationTargetException, NoSuchMethodException {

if (objList == null || objList.size() == 0)

throw new IllegalArgumentException("No objList specified");

if (propertyName == null || "".equals(propertyName)) {

throw new IllegalArgumentException("No propertyName specified for bean class '" + objList.get(0).getClass() + "'");

}

PropertyUtilsBean p = new PropertyUtilsBean();

List propList = new LinkedList();

for (int i = 0; i < objList.size(); i++) {

T obj = objList.get(i);

propList.add(p.getProperty(obj, propertyName));

}

return propList;

}

/**

* 将List列表中的对象的某个属性封装成一个Map对象,key值是属性名,value值是对象列表中对象属性值的列表

*

* @param objList

*            对象列表

* @param propertyName

*            属性名称,可以是一个或者多个

* @return 返回封装了属性名称和属性值列表的Map对象,如果参数非法则抛出异常信息

* @throws IllegalAccessException

* @throws InvocationTargetException

* @throws NoSuchMethodException

*/

public static Map> getPropertiesMap(List objList, String... propertyName)

throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

if (objList == null || objList.size() == 0)

throw new IllegalArgumentException("No objList specified");

if (propertyName == null || propertyName.length == 0) {

throw new IllegalArgumentException("No propertyName specified for bean class '" + objList.get(0).getClass() + "'");

}

Map> maps = new HashMap>();

for (int i = 0; i < propertyName.length; i++) {

maps.put(propertyName[i], getPropertyList(objList, propertyName[i]));

}

return maps;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值