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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM