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);

	}
}
相关推荐
CoderYanger几秒前
A.每日一题——2141.同时运行N台电脑的最长时间
java·算法·leetcode·职场和发展·1024程序员节
旺仔Sec几秒前
2025年广东省职业院校技能大赛应用软件系统开发赛项(高职组)赛题(一)
java·应用软件系统开发
雨中飘荡的记忆6 分钟前
Spring AI + Redis 向量库实战
java·redis·spring
CC.GG9 分钟前
【C++】面向对象三大特性之一——继承
java·数据库·c++
零匠学堂202511 分钟前
woapi-server为Office Online Server文档在线预览提供文档加载地址
java·运维·服务器·oos·wopi
Hui Baby12 分钟前
maven自动构建到镜像仓库
java·maven
czlczl2002092519 分钟前
SpringBoot手动配置:WebMvcConfigurer接口实现类的生效原理
java·spring boot·后端
程序员皮皮林20 分钟前
SpringBoot + nmap4j 获取端口信息
java·spring boot·后端
小二·21 分钟前
Spring框架入门:Spring 中注解支持详解
java·后端·spring
豐儀麟阁贵25 分钟前
8.6运行时异常
java·开发语言