Java数组去重 集合List去重的常用方法

文章介绍了在Java中删除数组和List中重复元素的五种常见方法,包括双重循环、HashMap、HashSet、迭代器以及JDK1.8Stream流。每种方法的特点和适用场景都被详细阐述。
摘要由CSDN通过智能技术生成

数组去重

Java删除数组中重复元素的常用方法:

方法一:for双重循环
  1. 声明int类型index,该数即可为不重复元素下标,还可统计数组中不重复元素的个数
  2. 第一层循环,遍历数组,取出每个元素
  3. 第二层循环,对第一层的元素进行判断是否重复,如果重复结束本次循环,否侧将该元素移动到赋值到相应下标数组
  4. 新建数组,长度为index,并将原数组的前index个元素赋值给新数组

实现代码:

public static void main(String[] args) {
        int[] array=new int[]{9,5,2,7,2,5,3,2,4};

       //准备新的数组,接收数据
        int[] newarray=new int[array.length];
        int index=0;
        for (int i=0;i<array.length;i++){
            for (int j=0;j<array.length;j++){
                if (i!=j){
                    if (array[i]==array[j]){//存在重复元素,结束本次循环
                        break;
                    }
                }
                if (j==array.length-1){//遍历结束,且没有重复元素
                    newarray[index]=array[i];
                    index++;
                }
            }
        }
        for (int i=0;i<index;i++){
            System.out.print(newarray[i]+"  ");
        }

    }
方法二:使用HashMap

首先我们需要知道HashMap是什么?
HashMap是一个散列表,存储的内容是键值对映射(key–value)。
HashMap是无序的,不会记录插入的顺序
HashMap的Key和Value类型可以相同也可以不相同;如
HashMap<String,Integer> map=new HashMap<>();

因此实现逻辑如下:

  1. 创建以Integer为key,Boolean为value的HashMap;
  2. 遍历数组,并判断HashMap中是否存在该元素,不存在将该以该元素为key,true为value存储进HashMap,如果存在,就将该key的value赋值为false。
  3. 将HashMap中value为true的元素取出并赋值给新数组。

实现代码:

public static void main(String[] args) {
        int[] array=new int[]{9,5,2,7,5,2,3,2,4};
        HashMap<Integer,Boolean> hashMap=new HashMap<Integer,Boolean>();
        for (int i:array
             ) {
            if (!hashMap.containsKey(i)){//判断Hash表中是否存在该元素,不存在侧保存
                hashMap.put(i, true);
            }else {//Hash Map中存在该元素,表明该元素重复,侧将value赋值为false
                hashMap.put(i, false);
            }
        }
        //统计个数
        int count=0;
        for (boolean flag: hashMap.values()
             ) {
            if (flag){
                count+=1;
            }
        }
        //创建新数组
        int[] newarray=new int[count];
        int index=0;
        for (int number: hashMap.keySet()//遍历HashMap,将value为true的元素取出,赋值给新数组
             ) {
            if (hashMap.get(number)){//将不重复的值赋值给新数组
                newarray[index]=number;
                index++;
            }
        }
        //遍历输出
        for (int i:newarray
             ) {
            System.out.print(i+"  ");
        }

    }

集合List去重

Java中去除list集合中的重复元素方法:

1.使用for循环list中的所有元素然后删除重复
/**
 * 使用for循环删除list中的重复元素
 * @param list
 * @return
 */
public static List removeDuplicate1(List list) {
    for (int i = 0; i < list.size() - 1; i++) {
        for (int j = list.size() - 1; j > i; j--) {
            if (list.get(j).equals(list.get(i))) {
                list.remove(j);
            }
        }
    }
    return list;
}
2.使用HashSet删除重复元素
/**
 * 使用HashSet删除重复元素
 * @param list
 * @return
 */
public static List removeDuplicate2(List list) {
    HashSet h = new HashSet(list);
    list.clear();
    list.addAll(h);
    return list;
}
3.使用迭代器删除list中的重复元素
/**
 * 使用迭代器删除list中的重复元素
 */
public static void removeDuplicateWithOrder3(List list) {
    Set set = new HashSet();
    List newList = new ArrayList();
    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Object element = iter.next();
        if (set.add(element))
            newList.add(element);
    }
    list.clear();
    list.addAll(newList);
    System.out.println(" remove duplicate " + list);
}
4.把list里的对象遍历一遍,用list.contains(),如果不存在就放入到另外一个list集合中
/**
 * 把list里的对象遍历一遍,用list.contains(),如果不存在就放入到另外一个list集合中
 * @param list
 * @return
 */
public static List removeDuplicate4(List list) {
    List listTemp = new ArrayList();
    for (int i = 0; i < list.size(); i++) {
        if (!listTemp.contains(list.get(i))) {
            listTemp.add(list.get(i));
        }
    }
    return listTemp;
}
5.用JDK1.8 Stream流中对List进行去重:list.stream().distinct()
List list = (List) userList.stream().distinct().collect(Collectors.toList());
System.out.println(list);

 以上方法可以根据不同的需求和性能要求进行选择。例如,如果需要保持元素的顺序,可以使用Set或LinkedHashSet;如果对性能有较高要求,可以使用Stream流去重。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值