【JAVA - List】差集removeAll() 四种方法实现与优化

一、场景:

二、结论:

1. 四种方法耗时

三、代码:


一、场景:

  • 求差集 List1 - Lsit2

二、结论:

1. 四种方法耗时

初始条件方法名方法思路耗时

List1.size=319418

List2.size=284900

List..removeAll(Lsit2)1036987ms
removeAll_01List.contains()614859ms
removeAll_02运用Set 150ms推荐
removeAll_03用Set.contains()再优化112ms推荐

 

三、代码:

package com.privatecloud.core.util.collections;

import com.alibaba.fastjson2.JSON;
import com.privatecloud.core.util.file.FileIOUtil;
import com.privatecloud.core.util.file.FilesReadUtil;
import com.privatecloud.core.util.file.FilesUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.*;

@Slf4j
public class ListUtils<T> {
    public List<T> removeAll_01(List<T> source, List<T> destination) {
        List<T> result = new LinkedList<T>();
        for (T t : source) {
            if (!destination.contains(t)) {
                result.add(t);
            }
        }
        return result;
    }

    /**
     * 2,运用Set可以去重这一特性。效率有明显提升
     *
     * @param source
     * @param destination
     * @return
     */
    public List<T> removeAll_02(List<T> source, List<T> destination) {
        List<T> result = new LinkedList<T>();

        Map<T, Integer> sourceMap = new HashMap<T, Integer>();
        for (T t : source) {
            if (sourceMap.containsKey(t)) { //原集合中的重复值
                sourceMap.put(t, sourceMap.get(t) + 1);
            } else {
                sourceMap.put(t, 1);
            }
        }

        Set<T> all = new HashSet<T>(destination);
        for (Map.Entry<T, Integer> entry : sourceMap.entrySet()) {
            T key = entry.getKey();
            Integer value = entry.getValue();
            if (all.add(key)) {
                for (int i = 0; i < value; i++) {
                    result.add(key);
                }
            }
        }
        return result;
    }

    /**
     * 3,用Set.contains()再优化
     *
     * @param source
     * @param destination
     * @return
     */
    public List<T> removeAll_03(List<T> source, List<T> destination) {
        List<T> result = new LinkedList<T>();
        Set<T> destinationSet = new HashSet<T>(destination);
        for (T t : source) {
            if (!destinationSet.contains(t)) {
                result.add(t);
            }
        }
        return result;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ladymorgana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值