全部,
我有一个对象
public class Device {
public String getUserId() {
return userId;
}
public String getDeviceId() {
return deviceId;
}
}
我得到了所有的值列表
List<Device> uList = getList();
在列表中我有一个基于 userId 的重复值现在我想获得唯一列表,它将删除 userId 的重复值
我怎样才能实现它,我是 Java 的新手
最佳答案
最简单的方法是创建一个 Map
,其中键是 userId
:
Map<String, Device> map = new HashMap<>();
devices.forEach(d -> map.put(d.getUserId(), d));
List<Device> uniques = new ArrayList<>(map.values());
或者,使用流:
Map<String, Device> map = devices.stream()
.collect(Collectors.toMap(Device::getUserId, d -> d, (a, b) -> a));
List<Device> uniques = new ArrayList<>(map.values());
或者,您可以将它们转储到 TreeSet
中,并使用检查 userId
的比较器:
Set<Device> set = new TreeSet<>(Comparator.comparing(Device::getUserId));
set.addAll(devices);
List<Device> uniques = new ArrayList<>(set);
所有这些都假设您不关心 deviceId
中的差异。否则,看看Map.merge()
或对应的Collectors.toMap()
过载。
关于java - 删除 ArrayList 中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57470083/