当前位置: 首页 > news >正文

【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;}}

http://www.lryc.cn/news/164180.html

相关文章:

  • sql注入基本概念
  • AIGC系列:1.chatgpt可以用来做哪些事情?
  • End-to-End Object Detection with Transformers(论文解析)
  • 生成多样、真实的评论(2019 IEEE International Conference on Big Data )
  • 项目中应该使用nginx还是拦截器来封禁IP
  • SMB 协议详解之-NTLM身份认证
  • day34 Set
  • 数据库_之常用API的使用
  • CTreeCtrl自绘
  • 目标检测YOLO实战应用案例100讲-基于深度学习的可见光遥感图像目标检测
  • MySQL数据库——存储引擎(2)-存储引擎特点(InnoDB、MyISAM、Memory)、存储引擎选择
  • 【Vue】构建vue项目的几种方法以及区别
  • 动态封装对象,属性来自json
  • 【LeetCode-中等题】90. 子集 II
  • Docker如何安装seafile
  • 注册法国商标的步骤和时间
  • 一起学数据结构(6)——栈和队列
  • 【数据结构】二叉树的顺序结构-堆
  • 2024年java面试--mysql(2)
  • IllegalArgumentException
  • Git 概述命令、idea中的使用
  • 单片机之硬件记录
  • QQ文件传输协议研究
  • Qt/C++音视频开发51-推流到各种流媒体服务程序
  • LeetCode 35. 搜索插入位置
  • 7年经验之谈 —— Web测试是什么,有何特点?
  • 【数据结构】前言概况 - 树
  • MySQL——事务
  • 虚拟机Ubuntu操作系统最基本终端命令(安装包+详细解释+详细演示)
  • Android 11.0 当系统内置两个Launcher时默认设置Launcher3以外的那个Launcher为默认Launcher