Java如何删除一个对象中的重复项呢?
下文笔者讲述将一个对象中的重复项的删除方法分享,如下所示:
实现思路: 1.重写类中的hashcode和equals方法 2.将list对象放入一个set对象中即可达到自动去重的效果例:
package com.java265.other; import java.util.*; public class test { public static void main(String[] args) { /* * author:java265.com * list去重操作示例分享 * */ List<User> list = new ArrayList<>(); list.add(new User("1","xiaoming")); list.add(new User("2","xiaoming")); list.add(new User("3","xiaoming")); list.add(new User("4","xiaoming")); list.add(new User("4","xiaoming")); System.out.println(list); System.out.println("------------"); //去重 Set<User> set = new HashSet<>(); set.addAll(list); System.out.println(set); } } class User{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User() { } public User(String id,String name){ this.id = id; this.name = name; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(name, user.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。