Java List的去重方法

1. 使用HashSet实现List去重(无序)

    /**使用HashSet实现List去重(无序)
     *
     * @param list
     * */
    public static List removeDuplicationByHashSet(List<Integer> list) {
        HashSet set = new HashSet(list);
        //把List集合所有元素清空
        list.clear();
        //把HashSet对象添加至List集合
        list.addAll(set);
        return list;
    }

2. 使用TreeSet实现List去重(有序)

    /**使用TreeSet实现List去重(有序)
     *
     * @param list
     * */
    public static List removeDuplicationByTreeSet(List<Integer> list) {
        TreeSet set = new TreeSet(list);
        //把List集合所有元素清空
        list.clear();
        //把HashSet对象添加至List集合
        list.addAll(set);
        return list;
    }

总结

无序HashSet,有序TreeSet

参考Java List的五种去重方法及效率对比

posted @ 2020-04-17 15:14  if年少有为  阅读(662)  评论(0编辑  收藏  举报