List findIntersection & getUnion

List findIntersection & getUnion 求两个列表的交集和并集

复制代码
package zwf;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 列表工具类
 * 
 * @author ZengWenFeng
 * @date 2025.04.22
 * @mobile 13805029595
 * @email 117791303@qq.com
 */
public class ListUtil
{
	/**
	 * 计算两个列表的交集
	 *
	 * @param listA [1,2,3,4,5]
	 * @param listB [ 2, 4,5,7,8]
	 * @return listC [ 2, 4,5]
	 */
	public static List<Long> findIntersection(List<Long> listA, List<Long> listB)
	{
		if (listA == null || listA.size() <= 0 || listB == null || listB.size() <= 0)
		{
			return null;
		}

		List<Long> result = new ArrayList<Long>();
		for (Long element : listA)
		{
			if (listB.contains(element))
			{
				result.add(element);
			}
		}

		return result;
	}

	/**
	 * 计算两个列表的并集
	 *
	 * @param listA [1,2,3,4,5]
	 * @param listB [ 2, 4,5,7,8]
	 * @return listC [1,2,3,4,5,7,8]
	 */
	public static List<Long> getUnion(List<Long> listA, List<Long> listB)
	{
		if (listA == null && listB == null)
		{
			return new ArrayList<Long>();
		}

		if (listA == null)
		{
			return new ArrayList<Long>(new LinkedHashSet<Long>(listB));
		}

		if (listB == null)
		{
			return new ArrayList<Long>(new LinkedHashSet<Long>(listA));
		}

		LinkedHashSet<Long> unionSet = new LinkedHashSet<>(listA.size() + listB.size());
		if (listA.size() > 0)
		{
			unionSet.addAll(listA);
		}

		if (listB.size() > 0)
		{
			unionSet.addAll(listB);
		}

		return new ArrayList<Long>(unionSet);
	}

	public static void main(String[] args)
	{
		// 初始化列表 A 和 B
		List<Long> listA = new ArrayList<>();
		listA.add(1L);
		listA.add(2L);
		listA.add(3L);
		listA.add(4L);
		listA.add(5L);

		List<Long> listB = new ArrayList<>();
		listB.add(2L);
		listB.add(4L);
		listB.add(5L);
		listB.add(7L);

		// 计算交集
		List<Long> intersection = findIntersection(listA, listB);

		// 输出交集
		System.out.println("交集列表: " + intersection);

		// 计算并集
		List<Long> union = getUnion(listA, listB);

		// 输出并集
		System.out.println("并集列表: " + union);

	}
}
相关推荐
SirLancelot11 小时前
数据结构-Set集合(一)Set集合介绍、优缺点
java·开发语言·数据结构·后端·算法·哈希算法·set
haaaaaaarry1 小时前
Element Plus常见基础组件(一)
java·前端·javascript·vue.js
歌者長門1 小时前
做题笔记:某大讯飞真题28道
java·数据结构·算法
Savvy..1 小时前
Day05 Maven
java·junit·maven·注解
Goboy2 小时前
我是如何设计出高性能群消息已读回执系统的
java·后端·架构
阳光明媚sunny2 小时前
结构型设计模式
java·设计模式
码luffyliu2 小时前
Java:高频面试知识分享1
java·八股文
小信丶2 小时前
Spring Boot 简单接口角色授权检查实现
java·spring boot·后端
IT乐手2 小时前
java 或 安卓项目中耗时统计工具类
android·java
草字2 小时前
uniapp 如果进入页面输入框自动聚焦,此时快速返回页面或者跳转到下一个页面,输入法顶上来的页面出现半屏的黑屏问题。
java·前端·uni-app