下文笔者讲述list对象的去重方法分享,list的实现类是我们存储数据的容器,
当里面存储的对象存在重复值时,我们该如何对其进行去重操作呢?
下文笔者将一一道来,首先我们需了解对象是否重复,需借助equals方法进行判断,所以我们需重写equals方法,
然后再将list中的数据放入到set集合中,使其自动去重,如下所示:
实现思路: 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); } }
转自:http://java265.com/JavaJingYan/202112/16385440541991.html
标签:name,对象,list,id,User,数据,public,String From: https://www.cnblogs.com/javalove2022/p/16723008.html