List去重的6种方法

本文详细介绍了在Java编程中如何对List进行去重,包括使用HashSet、Stream API、Lambda表达式等6种高效方法,帮助开发者优化代码,提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.demo;

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

/**
 * @创建人: lzc
 * @创建时间: 2022/7/17
 * @描述: TODO
 * @版本:1.0
 */
public class ListRepeat {
    /**
     * List去重的7中方法
     */
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 3, 2, 5, 6, 10, 1, 11, 32));
        System.out.println("list去重前:" + list);
        System.out.println("方法1:"+QuChong.linkedHashSet(list));
        System.out.println("方法2:"+QuChong.stream(list));
        System.out.println("方法3:"+QuChong.hashSet(list));
        System.out.println("方法4:"+QuChong.contains(list));
        System.out.println("方法5:"+QuChong.remove(list));
        System.out.println("方法6:"+QuChong.treeSet(list));
    }
}

/**
 * 创建去重实现方法
 */
class QuChong {

    /*方法1:LinkedHashSet去重*/
    public static List<Integer> linkedHashSet(List<Integer> list) {
        LinkedHashSet<Integer> Integer = new LinkedHashSet<>(list);
        return new ArrayList<>(Integer);
    }

    /*方法2:利用java1.8新特性stream流*/
    public static List<Integer> stream(List<Integer> list) {
        List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
        return new ArrayList<>(collect);
    }

    /*方法3:通过HashSet去重,但不能保证添加顺序*/
    public static List<Integer> hashSet(List<Integer> list) {
        HashSet<Integer> integers = new HashSet<>(list);
        return new ArrayList<>(integers);
    }

    /*方法4:通过List中contains方法循环遍历去重*/
    public static List<Integer> contains(List<Integer> list) {
        ArrayList<Integer> integers = new ArrayList<>(list.size());
        for (Integer i : list) {
            if (!integers.contains(i)) {
                integers.add(i);
            }
        }
        return new ArrayList<>(integers);
    }

    /*方法5:通过List中remove方法双重for循环遍历去重*/
    public static List<Integer> remove(List<Integer> list){
        for (int i=0;i<list.size();i++){
            for (int j=0;j<list.size();j++){
                if (i!=j&&list.get(i).equals(list.get(j))){
                    list.remove(list.get(i));
                }
            }
        }
        return new ArrayList<>(list);
    }

    /*方法6:TreeSet去重*/
    public static List<Integer> treeSet(List<Integer> list){
        TreeSet<Integer> integers = new TreeSet<>(list);
        return new ArrayList<>(integers);
    }

}

打印输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值