实现代码 /** * 将一个List 按某Object中个字段分组,Map 为最终结果 */ public static Map packetList(List list, String column){ Map maps = new HashMap (); int flag = 0; try { if (list.size()0){ T t = list.get(0); Field[] de
实现代码
/**
* 将一个List按某Object中个字段分组,Map
为最终结果 */ public static
Map
> packetList(List
list, String column){ Map
> maps = new HashMap
>(); int flag = 0; try { if (list.size()>0){ T t = list.get(0); Field[] declaredFields = t.getClass().getDeclaredFields(); for (int i = 0; i < declaredFields.length; i++) { if (declaredFields[i].getName().equals(column)){ //存在指定属性 flag = 1; break; } } if (flag == 0) { //不存在指定属性 return maps; } for ( T obj :list) { Object value = getValueByFiled(obj, column); if (maps.containsKey(value)){ //maps包含该键 maps.get(value).add(obj); }else{ maps.put(value,new ArrayList<>()); maps.get(value).add(obj); } } } } catch (SecurityException e) { e.printStackTrace(); } return maps; } /** * 通过对象和具体的字段名字获得字段的值 * @param obj 目的对象 * @param filed 字段名 * @return 通过字段名得到字段值 */ public static Object getValueByFiled(Object obj,String filed) { try { Class clazz = obj.getClass(); PropertyDescriptor pd = new PropertyDescriptor(filed,clazz); //获得get方法 Method getMethod = pd.getReadMethod(); //执行get方法返回一个Object Object o = getMethod.invoke(obj); return o; }catch (Exception e) { e.printStackTrace(); return null; } }
测试代码,从两个class中拉出来的,
@Test
public void test2(){
List
list = new ArrayList<>();
for (int i = 0; i < 50; i++) {
JustObj justObj = ObjFactory.JustObjRandom();
list.add(justObj);
}
Map
> str = CollectionsUtils.packetList(list, "str"); System.out.println("OJBK"); } public class ObjFactory { private final static char[] chars ={'1','2','3','4','5','6','7','8','9','x'}; public static JustObj JustObjRandom(){ JustObj justObj = new JustObj(); justObj.setDou(Math.random()); justObj.setDat(new Date()); int i = (int)(Math.random()*10-1); char c = chars[i]; justObj.setStr(String.valueOf(c)); return justObj; } }