- 1.java按照list集合中的对象属性进行去重
有时候我们需要对List集合进行去重,但是去重的集合不是String,Integer等简单的数据类型,而是复杂的对象类型,并且是根据List集合中的对象的指定属性进行去重,我这里封装了一个方法,是根据jdk源码来的,不需要引入任何第三方依赖,无任何侵入性。非常的灵活,可以指定任意属性进行去重。
具体看代码:
public class DistinctListTest {
public static void main(String[] args) throws Exception {
User userInfo1 = new User("1", "admin");
User userInfo2 = new User("2", "root");
User userInfo4 = new User("3", "admin");
User userInfo3 = new User("4", "jack");
List userInfoList = Arrays.asList(userInfo1, userInfo2, userInfo3, userInfo4);
System.out.println(distinctListForAttribute(userInfoList,"name"));
}
public static Object getFieldValue(Object target, String filedName) {
if (target == null || filedName == null || filedName.trim().length()<=0){
throw new ArithmeticException("target 或 filedName 不能为空!");
}
Class> clazz = target.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.getName().equals(filedName)) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException("根据对象属性名获取属性值发生错误:" + e.getMessage());
}
}
}
throw new RuntimeException("未能根据对象属性名获取属性值");
}
public static List distinctListForAttribute(List userInfoList,String filedName) {
List filteredList = new ArrayList<>();
Map 


