1. 程式人生 > 其它 >如何實現 List 集合去重?

如何實現 List 集合去重?

List 去重指的是將 List 中的重複元素刪除掉的過程。

List 去重有以下 6 種實現思路:

  1. 自定義方法去重,通過迴圈判斷當前的元素是否存在多個,如果存在多個,則刪除此重複項,迴圈整個集合最終得到的就是一個沒有重複元素的 List;
  2. 使用 Set 集合去重,利用 Set 集合自身自帶去重功能的特性,實現 List 的去重;
  3. 使用 JDK 8 中 Stream 流的去重功能。

    1.自定義去重(contains判斷去重(有序))

    自定義去重的實現方法有兩種,首先我們可以建立一個新集合,通過迴圈原集合判斷迴圈的元素,是否已存在於新集合,如果不存在則插入,否則就忽略,這樣迴圈完,最終得到的新集合就是一個沒有重複元素的集合,具體實現程式碼如下:

     
    public class DistinctExample {
        public static void main(String[] args) {
            // 建立並給 List 賦值
            List<Person> list = new ArrayList<>();
            list.add(new Person("李四", "123456", 20));
            list.add(new Person("張三", "123456", 18));
            list.add(new Person("王五", "123456", 22));
            list.add(new Person("張三", "123456", 18));
            // 去重操作
            List<Person> newList = new ArrayList<>(list.size());
            list.forEach(i -> {
                if (!newList.contains(i)) { // 如果新集合中不存在則插入newList.add(i);
                }
            });
            // 列印集合newList.forEach(p -> System.out.println(p));
        }
    }
     
    @Data
    class Person {
        private String name;
        private String password;
        private int age;
     
        public Person(String name, String password, int age) {
            this.name = name;
            this.password = password;
            this.age = age;
        }
    }
    

      執行結果如下

    2.利用set去重

    Set 集合天生具備去重特性,在建立 Set 集合時可以傳遞一個 List 集合,這樣就能實現資料轉移和去重的功能了,具體實現程式碼如下:

     
    public class DistinctExample {
        public static void main(String[] args) {
            // 建立並給 List 賦值
            List<Person> list = new ArrayList<>();
            list.add(new Person("李四", "123456", 20));
            list.add(new Person("張三", "123456", 18));
            list.add(new Person("王五", "123456", 22));
            list.add(new Person("張三", "123456", 18));
            // 去重操作
            HashSet<Person> set = new HashSet<>(list);
            // 列印集合資訊set.forEach(p -> System.out.println(p));
        }
    }
     
    @Data
    class Person {
        private String name;
        private String password;
        private int age;
     
        public Person(String name, String password, int age) {
            this.name = name;
            this.password = password;
            this.age = age;
        }
    }
    

      執行結果如下

    通過上述結果,發現了一個問題,在使用了 HashSet 去重之後,元素的先後順序發生了變化。為了能解決這個問題,我們可以使用 LinkedHashSet 來實現去重功能,具體實現程式碼如下:

     
    public class DistinctExample {
        public static void main(String[] args) {
            // 建立並給 List 賦值
            List<Person> list = new ArrayList<>();
            list.add(new Person("李四", "123456", 20));
            list.add(new Person("張三", "123456", 18));
            list.add(new Person("王五", "123456", 22));
            list.add(new Person("張三", "123456", 18));
            // 去重操作
            LinkedHashSet<Person> set = new LinkedHashSet<>(list);
            // 列印集合資訊set.forEach(p -> System.out.println(p));
        }
    }
     
    @Data
    class Person {
        private String name;
        private String password;
        private int age;
     
        public Person(String name, String password, int age) {
            this.name = name;
            this.password = password;
            this.age = age;
        }
    }
    

      執行結果如下

    3.使用 Stream 去重

    最後一種也是最簡單的一種去重方式,我們可以使用 JDK 8 中提供的 Stream 進行去重,Stream 中包含了一個去重方法:distinct,可以直接實現集合的去重功能,具體實現程式碼如下:

     
    public class DistinctExample {
        public static void main(String[] args) {
            // 建立並給 List 賦值
            List<Person> list = new ArrayList<>();
            list.add(new Person("李四", "123456", 20));
            list.add(new Person("張三", "123456", 18));
            list.add(new Person("王五", "123456", 22));
            list.add(new Person("張三", "123456", 18));
            // 去重操作
            list = list.stream().distinct().collect(Collectors.toList());
            // 列印集合資訊
            list.forEach(p -> System.out.println(p));
        }
    }
     
    @Data
    class Person {
        private String name;
        private String password;
        private int age;
     
        public Person(String name, String password, int age) {
            this.name = name;
            this.password = password;
            this.age = age;
        }
    }
    

      執行結果如下

     

    4.迭代器去重(無序)

    public static void main(String[] args) {
            List<Integer> list = new ArrayList<Integer>() {{
                add(1);
                add(3);
                add(5);
                add(2);
                add(1);
                add(3);
                add(7);
                add(2);
            }};
            System.out.println("原來的集合---"+list);
    
            Iterator<Integer> iterator = list.iterator();
            while(iterator.hasNext()){
                // 獲取迴圈的值
                Integer next = iterator.next();
                // 如果存在兩個相同的值
                if (list.indexOf(next) != list.lastIndexOf(next)){
                    // 移除最後那個相同的值
                    iterator.remove();
                }
            }
            System.out.println("去重集合:" + list);
        }
    

      執行結果如下

    5.TreeSet去重(無序)

    public static void main(String[] args) {
            List<Integer> list = new ArrayList<Integer>() {{
                add(1);
                add(3);
                add(5);
                add(2);
                add(1);
                add(3);
                add(7);
                add(2);
            }};
            System.out.println("原來的集合---"+list);
            TreeSet<Integer> set = new TreeSet<>(list);
            System.out.println("去重集合:" + set);
        }
    

      執行結果如下

    總結

    本文介紹了 5 種集合去重的方法,其中實現最簡潔,且去重之後的順序能和原集合保持一致的實現方法,只有兩種:LinkedHashSet 去重和 Stream 去重

    LinkedHashSet 在去重的同時又保證了元素所在位置不被更改

    Stream 的distinct 方法 是 JDK 8 中新增的,優點是不但寫法簡單,而且無需建立新的集合,是實現去重功能的首選方法