通用List转map,支持任意属性与多属性分组
例如根据 名字和年龄还有班级 三个属性相同的分为一组 ,只需要在参数中输入对应的三个属性名即可
/** * <h1> 根据多属性进行list转map分组</h1> * 可以自行修改,稍稍修改就可以达到集合里指定属性去重的效果 * * @param list 要转换的集合 * @param strings 转换后Map的key值,例如根据name属性分组,这里就填写name * 如果是要求name和age属性都相同的分为一组,这里就填name,age,更多属性同理 * key值默认为属性名的字符串连接,如果要指定的key名修改代码的20行和22行即可 * @param <T> 集合里对象的泛型,Matrix * @return 根据属性分好组的Map */ public static <T> Map<String, List<T>> listToMap(List<T> list, String... strings) { Map<String, List<T>> 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<T> 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; }
相关推荐
-
JAVA限流工具类 java
2019-1-7
-
通用List转map,支持任意属性与多属性分组 java
2019-1-7
-
httpclient post推送数据 java
2019-1-12
-
Hystrix线程池配置 java
2019-1-7
-
使用poi将excel转换为html,适用本身有导出excel的而现在需要添加网页打印的功能 java
2019-1-8
-
java根据经纬度计算两点之间距离 java
2019-1-8
-
java web 二维码生成 java
2019-1-8
-
springboot-项目初始化常用配置 java
2019-1-13
-
web开发跨域请求头工具类 java
2019-1-13
-
判断手机号运营商 java
2019-1-12