list去重
程序员文章站
2022-05-23 21:05:08
...
List数据去重在开发中是十分常见的场景,下面为大家介绍一个简单的方法:利用Set去重,但根据存储元素的不同,可以分为以下两类:
1. List中存储的是基本数据类型
下面看一段示例代码:
public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "a", "b")); System.out.println(list);// 输出结果:[a, b, c, d, a, b] Set<String> set = new HashSet<>(list); List<String> newList = new ArrayList<>(set); System.out.println(newList);// 输出结果:[a, b, c, d] } } ———————————————— 原文链接:https://blog.csdn.net/weixin_40328662/article/details/99843102
2. List中存储的是对象类型
示例代码:
public class Test { public static void main(String[] args) { List<People> peopleList = new ArrayList<>(); peopleList.add(new People("Joey", "001")); peopleList.add(new People("Joey", "001")); peopleList.add(new People("Johnny", "002")); peopleList.add(new People("Route", "003")); peopleList.add(new People("Vans", "004")); Set<People> peopleSet = new HashSet<>(peopleList); System.out.println(peopleSet); } } public class People { private String name; private String addrNum; // 省略无参、有参构造器,get、set方法,toString方法 @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } People people = (People) obj; return Objects.equals(name, people.name) && Objects.equals(addrNum, people.addrNum); } @Override public int hashCode() { return Objects.hash(name, addrNum); } } ———————————————— 原文链接:https://blog.csdn.net/weixin_40328662/article/details/99843102
/** * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial capacity (16) and load factor (0.75). */ public HashSet() { map = new HashMap<>(); } /** * Object类中equlas的默认实现 */ public boolean equals(Object obj) { return (this == obj); }