删除ArrayList中的重复对象

时间:2019-08-13 01:34:22

标签: java arraylist comparator

全部

我有一个对象

public class Device {

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

}

我获得了所有值列表

     List<Device> uList = getList();

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

我如何实现它,我对Java还是很陌生

2 个答案:

答案 0 :(得分:5)

最简单的方法是创建一个密钥为Map的{​​{1}}:

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); 中的差异。否则,请查看Map.merge()或相应的Collectors.toMap()重载。

答案 1 :(得分:0)

通过覆盖equals和hashCode(为什么hashCode?读为this)来定义对象中的相等性,然后使用Set(如果顺序重要,则使用LinkedHashSet)而不是List。

    public class Device {

        // fields, constructors, getters, setters
        ...

        @Override
        public boolean equals(final Object obj) {

            if (obj == this)
                return true;

            if (!(obj instanceof Device))
                return false;

            return Objects.equals(userId, ((Device) obj).userId);
        }

        @Override
        public int hashCode() {

            return Objects.hash(userId);
        }
    }

如果您绝对必须在列表末尾有一个列表,那么操作起来就很容易了。

final Set<Device> uniqueOrderedDevices = Sets.newLinkedHashSet(devicesList);
final List<Device> list = Lists.newArrayList(uniqueOrderedDevices);
相关问题