2 回答
TA贡献1836条经验 获得超4个赞
以下代码将删除重复项,并仅返回用户列表中的不同元素:
//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:说实话,由于这三个参数(生日,姓名和地址),这有点棘手。我现在能想到的最简单方法是实现hashCode并等于User类中的方法,例如(如果用户具有相同的三个值,则将其标记为相同):
@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;
}
TA贡献1887条经验 获得超5个赞
而不是 :List
List<User> users=new ArrayList<>();
您可以使用 a(我在此示例中使用了 ,):Set
HashSet
Set<User> users=new HashSet<>();
Sets
不允许重复,这样您甚至不需要过滤。
参见:https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
添加回答
举报