两个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值,我尝试过好些办法,在网上查的资料,都是说修改适配器, ...
随机推荐
- Git 分支
Git 保存的不是文件的变化或者差异,而是一系列不同时刻的文件快照,某一次的提交指向这处时刻的文件快照,看起来就像每次提交都保存了当时的文件,连续的提交形成一条长链 分支 指向某一个特定的提交,不同的 ...
- C++中的static关键字的总结
C++的static有两种用法:面向过程程序设计中的static和面向对象程序设计中的static.前者应用于普通变量和函数,不涉及类:后者主要说明static在类中的作用. 1.面向过程设计中的st ...
- html5移动web开发笔记(一)Web 存储
localStorage - 没有时间限制的数据存储 localStorage 方法 localStorage 方法存储的数据没有时间限制.第二天.第二周或下一年之后,数据依然可用. 用户访问页面的次 ...
- LLDB, iOS调试器
breakpoint set -s "" breakpoint set -M <method> ( --method <method> ) -S ...
- SSH整合开发的web.xml配置
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" ...
- 重读高程3: c2-3 script元素
1. 异步脚本一定会在页面的load事件前执行,但可能会在domC ontentLoaded事件触发之前或者之后执行.
- Hibernate的增删改查
一.搭建Hibernate开发环境,这里就不说了,直接说环境搭好后的事情. 二.项目的目录结构
- css cursor 的可选值(鼠标的各种样式)
crosshair; 十字准心 The cursor render as a crosshair游标表现为十字准线 cursor: pointer; cursor: hand;写两个是为了照顾IE5, ...
- 移动混合开发之android文件管理-->flexbox,webFont。
增加操作栏,使用felxbox居中,felx相关参考网址:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html 使用webFont添加图标, ...
- mount: /dev/sdb1 already mounted or /mnt/hdb busy 导致NameNode无法启动
最近,公司由于断电导致的服务器关机,等到来电了,重启集群发现Namenode无法启动,查看原因是由于无法加在faimage文件,在查看一下Namenode的磁盘挂在情况(df -h命令查看),发现磁盘 ...