今天碰到一个需要将 list 数组去重的问题,在网上一番搜索找到一个非常有用而且简洁的代码,记录一下。
方法的原理是将 list 数组转化为 set 数组。 因为 set 数组的特性来保证数据没有重复。
但是有一点需要注意,就是需要去重的对象一定要重写 equlas 和 hashCode 方法。
例子:
public class User { private String id; private String name; private int age; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LongitudeView)) return false; LongitudeView that = (LongitudeView) o; if (age != that.age) return false; return (id != null ? id.equals(that.id) : that.id == null) && (getName() != null ? getName().equals(that.getName()) : that.getName() == null); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (getName() != null ? getName().hashCode() : 0); result = 31 * result + age; return result; } }去重
List<User> userList = new ArrayList<>(); userList.add(new User("1", "peter", 18)); userList.add(new User("2", "stark", 25)); userList.add(new User("3", "peter", 22)); Set<User> userSet = new HashSet<>(userList); List<User> list = new ArrayList<>(userSet); list.forEach(System.out::println);