1、创建一个对象实体
public static class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2、去重方法
/**
* List去重
* @param tList 对象列表
* @param function 实现apply方法,获取去重属性值
* @param <T> 泛型去重对象
* @param <R> 泛型去重属性值
* @return 去重之后的列表
*/
public static <T, R> List<T> distinctByKey(List<T> tList, Function<? super T, R> function) {
List<T> otherList = new ArrayList<>();
Set<R> set = new ConcurrentSet<>();
for (T t : tList) {
R r = function.apply(t);
if (!set.contains(r)) {
set.add(r);
otherList.add(t);
}
}
return otherList;
}
3、使用方法
User user1 = new User("111", "pass");
User user2 = new User("111", "ddd");
User user3 = new User("222", "lll");
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
System.out.println("Before: " + userList);
System.out.println("After: " + distinctByKey(userList, User::getUsername));
运行结果
Before: [User{username='111', password='pass'}, User{username='111', password='ddd'}, User{username='222', password='lll'}]
After: [User{username='111', password='pass'}, User{username='222', password='lll'}]
4、总结
上面这个默认保存最开始出现的值,可以根据自己的需求修改对象保存先后顺序