如何使用 Java 删除 ArrayList 中的重复元素

如何使用 Java 删除 ArrayList 中的重复元素 (How to Remove Duplicates from ArrayList in Java)

Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java.

import java.util.*;
import java.util.stream.Collectors;

/**
 * RemoveDuplicateElements class
 * How to Remove Duplicates from ArrayList in Java
 * Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java.
 * https://www.geeksforgeeks.org/how-to-remove-duplicates-from-arraylist-in-java/
 *
 * @author libin
 * @date 2019/3/7 14:51
 */
public class RemoveDuplicateElements {
    public static void main(String[] args) {
        System.out.println("采用迭代去重: ");
        List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
        System.out.println("去重前: " + list);
        System.out.println("去重后: " + removeDuplicateElements(list));

        System.out.println("\n采用Set去重: ");
        List<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
        System.out.println("去重前: " + arrayList);
        System.out.println("去重后: " + removeDuplicateElementsBySet(arrayList));

        System.out.println("\n采用Java 8 Stream.distinct()去重: ");
        List<Integer> Java8List = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
        System.out.println("去重前: " + Java8List);
        List<Integer> resultList = Java8List.stream().distinct().collect(Collectors.toList());
        System.out.println("去重后: " + resultList);
    }

    // 采用迭代去重
    public static <T> List<T> removeDuplicateElements(List<T> list) {
        List<T> resultList = new ArrayList<T>();
        for (T t : list) {
            if (!resultList.contains(t)) {
                resultList.add(t);
            }
        }
        return resultList;
    }

    // 采用Set去重
    public static <T> List<T> removeDuplicateElementsBySet(List<T> list) {
        Set<T> set = new LinkedHashSet<T>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }
}

点击查看结果

采用迭代去重: 
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]

采用Set去重: 
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]

采用Java 8 Stream.distinct()去重: 
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]

Process finished with exit code 0

参考链接

转载于:https://www.cnblogs.com/hglibin/p/10490540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值