例如根据 名字和年龄还有班级 三个属性相同的分为一组 ,只需要在参数中输入对应的三个属性名即可
/**
*
根据多属性进行list转map分组
* 可以自行修改,稍稍修改就可以达到集合里指定属性去重的效果
*
* @param list 要转换的集合
* @param strings 转换后Map的key值,例如根据name属性分组,这里就填写name
* 如果是要求name和age属性都相同的分为一组,这里就填name,age,更多属性同理
* key值默认为属性名的字符串连接,如果要指定的key名修改代码的20行和22行即可
* @param 集合里对象的泛型,Matrix
* @return 根据属性分好组的Map
*/
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;
}