List 集合去重合并 , 多种方法演示

最近空闲时间去面试 , 被问了一个问题list如何去重合并 , 想了半天只想到了最繁琐的循环方法 , 顿觉丢人.
整理一下资料供大家参考

List<String> a = new ArrayList<String>();
a.add("2");
a.add("4");
a.add("5");
a.add("6");
List<String> b = new ArrayList<String>();
b.add("2");
b.add("3");
b.add("6");
b.add("7");

1.集合自带的api

这种方式看似挺方便 , 但是其底层还是遍历的去重 , 如果数据量太大还是不建议使用

public static void sortListTwo(List<String> a, List<String> b) {
		System.out.println("removeAll***************************");
		a.removeAll(b);
		a.addAll(b);
		for (String str2 : a) {
			System.out.println(str2);
		}
}

2.Set 方式 , 其本身就是不重复的集合

	public static void sortListOne(List<String> a, List<String> b) {
	    System.out.println("HashSet****************");
		Set<String> set = new HashSet<String>();
		set.addAll(a);
		set.addAll(b);
		List<String> c = new ArrayList<String>(set);
		for (String str : c) {
			System.out.println(str);
		}
	}

3.Map 方式 , key 是唯一的

这种方式可以去重 ,但是需要遍历两个list , 还是较为繁琐

	public static void sortListFree(List<String> a, List<String> b) {
		System.out.println("Map***************************");
		Map<String, Object> map = new HashMap<String, Object>();
		for (String str : a) {
			map.put(str, str);
		}
		for (String str1 : b) {
			map.put(str1, str1);
		}
		for(Map.Entry<String , Object> entry : map.entrySet()){
			System.out.println(entry.getKey()+":"+entry.getValue());
		}
	}

**注意:**以上的几种方式都是针对的基本数据类型 , 如果是对象的话会有一些问题

关注回复【资料】,免费获取架构资料、视频,还有精心整理的面试题
在这里插入图片描述

发布了58 篇原创文章 · 获赞 40 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/xinzhifu1/article/details/59058259