删除ArrayList中的重复对象

kir*_*iri 1 java arraylist comparator

所有,

我有一个对象

public class Device {

     public String getUserId() {
        return userId;
    }
    public String getDeviceId() {
        return deviceId;
    }

}
Run Code Online (Sandbox Code Playgroud)

我得到了所有的价值清单

     List<Device> uList = getList();
Run Code Online (Sandbox Code Playgroud)

在列表中,我有一个基于userId的重复值现在我要获取“唯一”列表,该列表将删除userId的重复项

我要如何实现它,我是Java的新手

shm*_*sel 5

最简单的方法是创建一个Map键,其中键为userId

Map<String, Device> map = new HashMap<>();
devices.forEach(d -> map.put(d.getUserId(), d));
List<Device> uniques = new ArrayList<>(map.values());
Run Code Online (Sandbox Code Playgroud)

或者,使用流:

Map<String, Device> map = devices.stream()
        .collect(Collectors.toMap(Device::getUserId, d -> d, (a, b) -> a));
List<Device> uniques = new ArrayList<>(map.values());
Run Code Online (Sandbox Code Playgroud)

或者,您可以将它们转储到TreeSet具有以下比较器的比较器中userId

Set<Device> set = new TreeSet<>(Comparator.comparing(Device::getUserId));
set.addAll(devices);
List<Device> uniques = new ArrayList<>(set);
Run Code Online (Sandbox Code Playgroud)

所有这一切都假定您不担心中的差异deviceId。否则,请查看Map.merge()或相应的Collectors.toMap()过载。