List 去重的 6 种方法

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

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);
    }
}

  

MC❤涛
原文地址:https://www.cnblogs.com/aikutao/p/15722830.html