这是我的代码:
public class User{
private String id;
private String userName;
private Long birthDate;
private String address;
private boolean enabled;
//Constructors
// Getters && Setters
...
}
public class ServiceUser{
List<User> users=new ArrayList<>();
public ServiceUser(){
users.add(new User("OPS","MESSI",15454222454L,"ADRESSE 1",true))
users.add(new User("TA1","RICHARD",1245485456787L,"ADRESSE 1",true));
users.add(new User("XA5","LANG",659854575424L,"ADRESSE 2",true));
users.add(new User("DS7","RICHARD",1245485456787L,"ADRESSE 1",false));
users.add(new User("OPD6","LONG",659854575424L,"ADRESSE 2",false));
...
}
protected List<User> getFiltredUsers(){
// TODO here
}
}
我想获得一个用户列表,例如:
User("OPS","MESSI",15454222454L,"ADRESSE 1",true)
如何删除具有相同用户名、出生日期、地址的所有重复行?
Nb: the user list is returned by the database, and just for the example i put it like that.
最佳答案
以下代码删除重复项并仅返回用户列表中不同的元素:
//used for grouping them by name, birthday and address
static Function<User, List<Object>> groupingComponent = user ->
Arrays.<Object>asList(user.getName(), user.getBirthday(),user.getAddress());
//grouping method used for grouping them by groupingComponent and frequency of it
private static Map<Object, Long> grouping(final List<User> users) {
return users.stream()
.collect(Collectors.groupingBy(groupingComponent, Collectors.counting()));
}
//filtering method used for filtering lists if element is contained more than 1 within a list
private static List<Object> filtering(final Map<Object, Long> map) {
return map.keySet()
.stream()
.filter(key -> map.get(key) < 2)
.collect(Collectors.toList());
}
简单的用法是:filtering(grouping(users));
System.out.println(filtering(grouping(users)));
<小时/>
更新3: 老实说,由于这三个参数(生日、姓名和地址),这有点棘手。我现在能想到的最简单的方法是在 User 类中实现 hashCode 和 equals 方法(如果用户具有相同的三个值,则将用户标记为相同):
@Override
public int hashCode() {
return (43 + 777);
}
@Override
public boolean equals(Object obj) {
// checks to see whether the passed object is null, or if it’s typed as a
// different class. If it’s a different class then the objects are not equal.
if (obj == null || getClass() != obj.getClass()) {
return false;
}
// compares the objects’ fields.
User user = (User) obj;
return getName().contains(user.getName())
&& getBirthday() == user.getBirthday()
&& getAddress()== user.getAddress();
}
以及以下方法删除所有重复项
public static List<User> filter(List<User> users) {
Set<User> set = new HashSet<>();
List<User> uniqueUsers = new ArrayList<>();
List<User> doubleUsers = new ArrayList<>();
Map<Boolean, List<User>> partitions = users.stream().collect(Collectors.partitioningBy(user -> set.add(user) == true));
uniqueUsers.addAll(partitions.get(true));
doubleUsers.addAll(partitions.get(false));
uniqueUsers.removeAll(doubleUsers);
return uniqueUsers;
}
关于java - 如何在java 8中按列表对象的多个参数进行分组并删除重复的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55600065/