两个list取不同值
转自同名博文,未知真正出处,望作者见谅
如题:有List<String> list1和List<String> list2,两个集合各有上万个元素,怎样取出两个集合中不同的元素?
方法1:遍历两个集合:
- package com.czp.test;
- import java.util.ArrayList;
- import java.util.List;
- public class TestList {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- for (int i = 0; i < 10000; i++) {
- list1.add("test"+i);
- list2.add("test"+i*2);
- }
- getDiffrent(list1,list2);
- //输出:total times 2566454675
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- for(String str:list1)
- {
- if(!list2.contains(str))
- {
- diff.add(str);
- }
- }
- System.out.println("total times "+(System.nanoTime()-st));
- return diff;
- }
- }
千万不要采用这种方法,总共要循环的次数是两个List的size相乘的积,从输出看耗时也是比较长的,那么我们有没有其他的方法呢?当然有.
方法2:采用List提供的retainAll()方法:
- package com.czp.test;
- import java.util.ArrayList;
- import java.util.List;
- public class TestList {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- for (int i = 0; i < 10000; i++) {
- list1.add("test"+i);
- list2.add("test"+i*2);
- }
- getDiffrent(list1,list2);
- //输出:total times 2566454675
- getDiffrent2(list1,list2);
- //输出:getDiffrent2 total times 2787800964
- }
- /**
- * 获取连个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent2(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- list1.retainAll(list2);
- System.out.println("getDiffrent2 total times "+(System.nanoTime()-st));
- return list1;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- for(String str:list1)
- {
- if(!list2.contains(str))
- {
- diff.add(str);
- }
- }
- System.out.println("getDiffrent total times "+(System.nanoTime()-st));
- return diff;
- }
- }
- 很遗憾,这种方式虽然只要几行代码就搞定,但是这个却更耗时,查看retainAll()的源码:
- public boolean retainAll(Collection<?> c) {
- boolean modified = false;
- Iterator<E> e = iterator();
- while (e.hasNext()) {
- if (!c.contains(e.next())) {
- e.remove();
- modified = true;
- }
- }
- return modified;
- }
无需解释这个耗时是必然的,那么我们还有没有更好的办法呢?仔细分析以上两个方法中我都做了mXn次循环,其实完全没有必要循环这么多次,我们的需求是找出两个List中的不同元素,那么我可以这样考虑:用一个map存放lsit的所有元素,其中的key为lsit1的各个元素,value为该元素出现的次数,接着把list2的所有元素也放到map里,如果已经存在则value加1,最后我们只要取出map里value为1的元素即可,这样我们只需循环m+n次,大大减少了循环的次数。
- package com.czp.test;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class TestList {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- for (int i = 0; i < 10000; i++) {
- list1.add("test"+i);
- list2.add("test"+i*2);
- }
- getDiffrent(list1,list2);
- //输出:total times 2566454675
- getDiffrent2(list1,list2);
- //输出:getDiffrent2 total times 2787800964
- getDiffrent3(list1,list2);
- //输出:getDiffrent3 total times 61763995
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent3(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
- List<String> diff = new ArrayList<String>();
- for (String string : list1) {
- map.put(string, 1);
- }
- for (String string : list2) {
- Integer cc = map.get(string);
- if(cc!=null)
- {
- map.put(string, ++cc);
- continue;
- }
- map.put(string, 1);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent3 total times "+(System.nanoTime()-st));
- return list1;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent2(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- list1.retainAll(list2);
- System.out.println("getDiffrent2 total times "+(System.nanoTime()-st));
- return list1;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- for(String str:list1)
- {
- if(!list2.contains(str))
- {
- diff.add(str);
- }
- }
- System.out.println("getDiffrent total times "+(System.nanoTime()-st));
- return diff;
- }
- }
显然,这种方法大大减少耗时,是方法1的1/4,是方法2的1/40,这个性能的提升时相当可观的,但是,这不是最佳的解决方法,观察方法3我们只是随机取了一个list作为首次添加的标准,这样一旦我们的list2比list1的size大,则我们第二次put时的if判断也会耗时,做如下改进:
- package com.czp.test;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class TestList {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- for (int i = 0; i < 10000; i++) {
- list1.add("test"+i);
- list2.add("test"+i*2);
- }
- getDiffrent(list1,list2);
- getDiffrent2(list1,list2);
- getDiffrent3(list1,list2);
- getDiffrent4(list1,list2);
- // getDiffrent total times 2789492240
- // getDiffrent2 total times 3324502695
- // getDiffrent3 total times 24710682
- // getDiffrent4 total times 15627685
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent4(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
- List<String> diff = new ArrayList<String>();
- List<String> maxList = list1;
- List<String> minList = list2;
- if(list2.size()>list1.size())
- {
- maxList = list2;
- minList = list1;
- }
- for (String string : maxList) {
- map.put(string, 1);
- }
- for (String string : minList) {
- Integer cc = map.get(string);
- if(cc!=null)
- {
- map.put(string, ++cc);
- continue;
- }
- map.put(string, 1);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent4 total times "+(System.nanoTime()-st));
- return diff;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent3(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
- List<String> diff = new ArrayList<String>();
- for (String string : list1) {
- map.put(string, 1);
- }
- for (String string : list2) {
- Integer cc = map.get(string);
- if(cc!=null)
- {
- map.put(string, ++cc);
- continue;
- }
- map.put(string, 1);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent3 total times "+(System.nanoTime()-st));
- return diff;
- }
- /**
- * 获取连个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent2(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- list1.retainAll(list2);
- System.out.println("getDiffrent2 total times "+(System.nanoTime()-st));
- return list1;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- for(String str:list1)
- {
- if(!list2.contains(str))
- {
- diff.add(str);
- }
- }
- System.out.println("getDiffrent total times "+(System.nanoTime()-st));
- return diff;
- }
- }
这里对连个list的大小进行了判断,小的在最后添加,这样会减少循环里的判断,性能又有了一定的提升,正如一位朋友所说,编程是无止境的,只要你认真去思考了,总会找到更好的方法!
非常感谢binglian的指正,针对List有重复元素的问题,做以下修正,首先明确一点,两个List不管有多少个重复,只要重复的元素在两个List都能找到,则不应该包含在返回值里面,所以在做第二次循环时,这样判断:如果当前元素在map中找不到,则肯定需要添加到返回值中,如果能找到则value++,遍历完之后diff里面已经包含了只在list2里而没在list2里的元素,剩下的工作就是找到list1里有list2里没有的元素,遍历map取value为1的即可:
- package com.czp.test;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class TestList {
- public static void main(String[] args) {
- List<String> list1 = new ArrayList<String>();
- List<String> list2 = new ArrayList<String>();
- for (int i = 0; i < 10000; i++) {
- list1.add("test"+i);
- list2.add("test"+i*2);
- }
- getDiffrent(list1,list2);
- getDiffrent3(list1,list2);
- getDiffrent5(list1,list2);
- getDiffrent4(list1,list2);
- getDiffrent2(list1,list2);
- // getDiffrent3 total times 32271699
- // getDiffrent5 total times 12239545
- // getDiffrent4 total times 16786491
- // getDiffrent2 total times 2438731459
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent5(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- List<String> maxList = list1;
- List<String> minList = list2;
- if(list2.size()>list1.size())
- {
- maxList = list2;
- minList = list1;
- }
- Map<String,Integer> map = new HashMap<String,Integer>(maxList.size());
- for (String string : maxList) {
- map.put(string, 1);
- }
- for (String string : minList) {
- if(map.get(string)!=null)
- {
- map.put(string, 2);
- continue;
- }
- diff.add(string);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent5 total times "+(System.nanoTime()-st));
- return diff;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent4(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
- List<String> diff = new ArrayList<String>();
- List<String> maxList = list1;
- List<String> minList = list2;
- if(list2.size()>list1.size())
- {
- maxList = list2;
- minList = list1;
- }
- for (String string : maxList) {
- map.put(string, 1);
- }
- for (String string : minList) {
- Integer cc = map.get(string);
- if(cc!=null)
- {
- map.put(string, ++cc);
- continue;
- }
- map.put(string, 1);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent4 total times "+(System.nanoTime()-st));
- return diff;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent3(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- Map<String,Integer> map = new HashMap<String,Integer>(list1.size()+list2.size());
- List<String> diff = new ArrayList<String>();
- for (String string : list1) {
- map.put(string, 1);
- }
- for (String string : list2) {
- Integer cc = map.get(string);
- if(cc!=null)
- {
- map.put(string, ++cc);
- continue;
- }
- map.put(string, 1);
- }
- for(Map.Entry<String, Integer> entry:map.entrySet())
- {
- if(entry.getValue()==1)
- {
- diff.add(entry.getKey());
- }
- }
- System.out.println("getDiffrent3 total times "+(System.nanoTime()-st));
- return diff;
- }
- /**
- * 获取连个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent2(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- list1.retainAll(list2);
- System.out.println("getDiffrent2 total times "+(System.nanoTime()-st));
- return list1;
- }
- /**
- * 获取两个List的不同元素
- * @param list1
- * @param list2
- * @return
- */
- private static List<String> getDiffrent(List<String> list1, List<String> list2) {
- long st = System.nanoTime();
- List<String> diff = new ArrayList<String>();
- for(String str:list1)
- {
- if(!list2.contains(str))
- {
- diff.add(str);
- }
- }
- System.out.println("getDiffrent total times "+(System.nanoTime()-st));
- return diff;
- }
- }
两个list取不同值的更多相关文章
- vue中过滤器比较两个数组取相同值
在vue中需要比较两个数组取相同值 一个大数组一个 小数组,小数组是大数组的一部分取相同ID的不同name值 有两种写法,两个for循环和map写法 const toName = (ids, arr) ...
- jsp取addFlashAttribute值深入理解即springMVC发redirect传隐藏参数
结论:两种方式 a.如果没有进行action转发,在页面中el需要${sessionScope['org.springframework.web.servlet.support.SessionFlas ...
- hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
pog loves szh II Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) ...
- UVA 10859 - Placing Lampposts 树形DP、取双优值
Placing Lampposts As a part of the mission ‘Beautification of Dhaka City’, ...
- go 两个数组取并集
实际生产中,对不同数组取交集.并集.差集等场景很常用,下面来说下两个数组取差集 直接上代码: //两个集合取并集 package main import "fmt" //思想: / ...
- 定时ping取返回值并绘图
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- php取默认值以及类的继承
(1)对于php的默认值的使用和C++有点类似,都是在函数的输入中填写默认值,以下是php方法中对于默认值的应用: <?phpfunction makecoffee($types = array ...
- java中两个Integer类型的值相比较的问题
今天在做一个算法时,由于为了和其他人保持接口的数据类型一致,就把之前的int换为Integer,前几天测了几组数据,和之前的结果一样,但是今天在测其它数据 的时候,突然出现了一个奇怪的bug,由于之前 ...
- 在android的spinner中,实现取VALUE值和TEXT值。 ZT
在android的spinner中,实现取VALUE值和TEXT值. 为了实现在android的 spinner实现取VALUE值和TEXT值,我尝试过好些办法,在网上查的资料,都是说修改适配器, ...
随机推荐
- ros语音交互(四)移植科大讯飞语音识别到ros
将以前下载的的语音包的 samples/iat_record/的iat_record.c speech_recognizer.c speech_recognizer.c 拷贝到工程src中, linu ...
- ROS语音交互(三)科大讯飞语音在ROS平台下使用
以上节tts语音输出为例 下载sdk链接:http://www.xfyun.cn/sdk/dispatcher 1.下载SDK,解压: 2.在ROS工作空间下创建一个Package: catkin_c ...
- ICEM(1)—边界结构网格绘制
以两个圆为例 1. geometry→ create curve→ 选择圆,随便画两个圆 2. block下选择create block,选择第一项,initial block,设置改为2D Plan ...
- React Native 组件样式测试
View组件默认样式(注意默认flexDirection:'column') {flexGrow:0,flexShrink:0,flexBasis:'auto',flexDirection:'colu ...
- c# 字符串操作
一.字符串操作 //字符串转数组 string mystring="this is a string" char[] mychars=mystring.ToCharArray(); ...
- Emacs 相关资料翻译
Table of Contents 1. 37 Document Viewing 2. EmacsrelatedTranslation 2.1. Spacemacs 配置层(Configuration ...
- Dynamic Programming
We began our study of algorithmic techniques with greedy algorithms, which in some sense form the mo ...
- 横向滑动的GridView
思路: GridView行数设置为一行,外面套一个HorizontalScrollView,代码中设置GridView宽度 xml代码 <HorizontalScrollView android ...
- Java第六次作业修改版
import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class Draw ...
- 细说JAVA反射
Reflection 是 Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查,或者说“自审”,并能直接操作程序的内部属性.例如,使用它能获得 Java 类中各成员的名称并显 ...