定义根据属性类别封装放的方法:
/**
* @Description: 根据类别封装配置的方法
* @Author: mc 2023/5/31 18:52
*/
public <T> Map<Object, List<T>> groupListByProperty(List<T> list, String propertyName) {
Map<Object, List<T>> map = new HashMap<>();
if (list != null && !list.isEmpty()) {
for (T t : list) {
try {
// 通过反射获取属性值
Field field = t.getClass().getDeclaredField(propertyName);
field.setAccessible(true);
Object value = field.get(t);
// 将对象加入到相应的列表中,并添加到map中
List<T> subList = map.computeIfAbsent(value, k -> new ArrayList<>());
subList.add(t);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
return map;
}
方法调用:传入计划重装的集合以及类别属性即可
// 方法调用
Map<Object,List<Object>> map = new HashMap<>();
map = groupListByProperty(list, "type");