java两个大量数据的集合取交集、并集

java两个大量数据的集合取交集、并集,第1张

java两个大量数据的集合取交集、并集

工作上需要调第三方接口同步数据过来,一开始jsonString jsonObject转来转去一个同步接口得耗时5分钟,现在只需要0.5秒

1、反序列化相关json数据
//小括号里面的clazz非常重要
private static  Result parseResult(String json, Class clazz) {
    return JSONObject.parseObject(json, new TypeReference>(clazz) {
    });
}
2、增加相关实体的equals() 和hashcode()方法作为判断交并集的依据
	@Override
	public boolean equals(Object o)
	{
		if (this == o){
			return true;
		}

		if (o == null || getClass() != o.getClass()){
			return false;
		}


		JxbPoJo jxbPoJo = (JxbPoJo) o;

		return Id.equals(jxbPoJo.Id);
	}

	@Override
	public int hashCode()
	{
		return Id.hashCode();
	}
3、两个集合取交并集的方法
	public static  List receiveCollectionList(List firstArrayList, List secondArrayList)
	{
		if (firstArrayList == null || firstArrayList.size() == 0 || secondArrayList == null || secondArrayList.size() == 0)
		{
			return null;
		}
		
		linkedList result = new linkedList(firstArrayList);
		
		HashSet othHash = new HashSet(secondArrayList);
		
		result.removeIf(t -> !othHash.contains(t));

		return new ArrayList<>(result);
	}

	
	public static  List receiveDefectList(List firstArrayList, List secondArrayList)
	{
		List resultList = new ArrayList();
		// 大集合用linkedlist
		linkedList result = new linkedList(firstArrayList);
		// 小集合用hashset
		HashSet othHash = new HashSet(secondArrayList);
		// 采用Iterator迭代器进行数据的 *** 作
		result.removeIf(othHash::contains);
		resultList = new ArrayList<>(result);
		firstArrayList.clear();
		firstArrayList.addAll(resultList);
		return firstArrayList;
	}

相关文章:

https://blog.csdn.net/weixin_41922349/article/details/108759956

https://blog.csdn.net/tiger0709/article/details/81474461

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5608212.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存