首页 > 技术文章 > List去除重复元素

xpybsh 2021-06-30 16:33 原文

 1 import java.util.*;
 2 import java.util.stream.Collectors;
 3 
 4 public class ListDistinct {
 5     public static void main(String[] args) {
 6 
 7         List<Integer> list1 = Arrays.asList(1, 2, 3, 3, 4, 2, 6, 3, 7, 6);
 8         ArrayList<Integer> list = new ArrayList<>(list1);
 9 
10         List distinct = distinct3(list);
11         for (Object o : distinct) {
12             System.out.print(o + " ");
13         }
14     }
15     //双重循环遍历list,去除重复值
16     public static List distinct1(List list){
17         for (int i = 0; i < list.size()-1; i++) {//每次拿第i个元素
18             for (int j = list.size()-1; j > i ; j--) {//从最后一个元素开始往前比较
19                 if (list.get(j).equals(list.get(i))){//删除相同元素
20                     list.remove(j);
21                 }
22             }
23         }
24         return list;
25     }
26 
27     //通过Set的不重复特性去除重复元素
28     public static List distinct2(List list){
29         HashSet set = new HashSet<>(list);
30         list.clear();//删除之前所有元素
31         list.addAll(set);//搬运set中的所有元素
32         return list;
33     }
34 
35     //去重顺序不乱
36     public static List distinct3(List list){
37         HashSet set = new HashSet<>();
38         List<Object> newList = new ArrayList<>();
39         Iterator iterator = list.iterator();//用迭代器遍历
40         while (iterator.hasNext()){
41             Object element = iterator.next();
42             if (set.add(element)){//如果set添加了这个元素新列表也添加进去,set 的add()源码解释如下图
43                 newList.add(element);
44             }
45         }
46         list.clear();
47         list.addAll(newList);
48 
49         return list;
50     }
51     //把list里的对象遍历一遍,用list.contains(),如果不存在就放入到另外一个list集合中
52     public static List distinct4(List list){
53         List<Object> newList = new ArrayList<>();
54         for (int i = 0; i < list.size()-1; i++) {
55             if (!newList.contains(list.get(i))){
56                 newList.add(list.get(i));
57             }
58         }
59         list.clear();
60         list.addAll(newList);
61         return list;
62     }
63 
64     //用jdk1.8新特性stream
65     public static List distinct5(List list){
66         return  (List) list.stream().distinct().collect(Collectors.toList());
67 
68     }
69 
70 }

 

 

推荐阅读