本文共计295个文字,预计阅读时间需要2分钟。

例如,根据姓名、年龄和班级等三个属性相同的数据分为一组,只需在参数中输入对应的属性名即可。Java版本需要使用26++/* 数据多属性进行list转map分组,* @param list 需要转换的集合,shout to LDF * **

例如根据 名字和年龄还有班级 三个属性相同的分为一组 ,只需要在参数中输入对应的属性名即可,java版本要求6+
/**
*
根据多属性进行list转map分组
*
* @param list 要转换的集合 shout to LDF
* @param strings 作为key的string数组
* @param
集合里对象的泛型
* @return
*/
public static
Map
> listToMap(List
list, String... strings) { Map
> returnMap = new HashMap<>(); try { for (T t : list) { StringBuffer stringBuffer = new StringBuffer(); for (String s : strings) { Field name1 = t.getClass().getDeclaredField(s);//通过反射获得私有属性,这里捕获获取不到属性异常 name1.setAccessible(true);//获得访问和修改私有属性的权限 String key = name1.get(t).toString();//获得key值 stringBuffer.append(key); } String KeyName = stringBuffer.toString(); List
tempList = returnMap.get(KeyName); if (tempList == null) { tempList = new ArrayList<>(); tempList.add(t); returnMap.put(KeyName, tempList); } else { tempList.add(t); } } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return returnMap; }