一、List 集合对象去重

List 集合对象去重,可以通过利用 Set 的特性,将 List 集合转换为 Set 集合,然后再转换回 List 集合,就可以实现 List 集合去重的功能。具体实现步骤如下:

1、创建一个 Set 集合,将 List 集合的元素添加到 Set 集合中;

2、创建一个新的 List 集合,将 Set 集合的元素添加到新的 List 集合中;

3、将原来的 List 集合指向新的 List 集合。

List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(2);Set<Integer> set = new HashSet<>(list);List<Integer> newList = new ArrayList<>(set);list = newList;
Java

二、按属性去重

按属性去重,可以采用 Stream 的 distinct() 方法来实现。Stream 的 distinct() 方法可以根据指定的字段(属性)去重,具体实现步骤如下:

1、将 List 集合转换为 Stream 流;

2、调用 Stream 流的 distinct() 方法,按照指定的属性去重;

3、将 Stream 流转换为 List 集合。

List<Person> list = new ArrayList<>();list.add(new Person(1, "zhangsan"));list.add(new Person(2, "lisi"));list.add(new Person(1, "zhangsan"));List<Person> newList = list.stream().distinct().collect(Collectors.toList());list = newList;
Java