List 去重的 6 种方法

其中去重之后的顺序能和原集合保持一致的实现方法,只有两种:LinkedHashSet 去重和 Stream 去重,而后一种去重方法无需借助新集合,是我们优先考虑的去重方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class TestDemo{
    public static void main(String[] args) {
        //初始化集合数据
        List<Integer> list = new ArrayList<Integer>() {{
            add(1);
            add(9);
            add(8);
            add(2);
            add(12);
            add(9);
            add(7);
            add(2);
        }};
 
        //方法1:contains判断去重(有序)
        method_1(list);
        //方法2:迭代器去重(无序)
        method_2(list);
        //方法3:HashSet去重(无序) HashSet 天生具备“去重”的特性,那我们只需要将 List 集合转换成 HashSet 集合
        HashSet<Integer> set = new HashSet<>(list);
        //方法4:LinkedHashSet去重(有序) LinkedHashSet,它既能去重又能保证集合的顺序
        LinkedHashSet<Integer> linkSet= new LinkedHashSet<>(list);
        //方法5:TreeSet去重(无序)
        TreeSet<Integer> treeSet = new TreeSet<>(list);
        //方法6:JDK 8 Stream去重(有序)
        method_3(list);
 
    }
    public static  void method_1(List<Integer> list){
        // 新集合
        List<Integer> newList = new ArrayList<>(list.size());
        list.forEach(i -> {
            if (!newList.contains(i)) { // 如果新集合中不存在则插入
                newList.add(i);
            }
        });
        System.out.println("去重集合:" + newList);
    }
   public static  void method_2(List<Integer> list){
       Iterator<Integer> iterator = list.iterator();
       while (iterator.hasNext()) {
           // 获取循环的值
           Integer item = iterator.next();
           // 如果存在两个相同的值
           if (list.indexOf(item) != list.lastIndexOf(item)) {
               System.out.println(list.indexOf(item));
               // 移除最后那个相同的值
               iterator.remove();
           }
       }
       System.out.println("去重集合:" + list);
   }
    public static  void method_3(List<Integer> list){
        list = list.stream().distinct().collect(Collectors.toList());
        System.out.println("去重集合:" + list);
    }
}

  

posted @   自信的咸鱼  阅读(3979)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2019-12-23 SpringMVC 请求调用过程
点击右上角即可分享
微信分享提示