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

	}
}
相关推荐
稻草猫.10 分钟前
Java网络编程套接字
java·后端·java-ee·idea
云泽8082 小时前
函数模板与类模板:C++泛型编程核心解析
java·开发语言·c++
缺点内向6 小时前
Java:创建、读取或更新 Excel 文档
java·excel
带刺的坐椅6 小时前
Solon v3.4.7, v3.5.6, v3.6.1 发布(国产优秀应用开发框架)
java·spring·solon
四谎真好看8 小时前
Java 黑马程序员学习笔记(进阶篇18)
java·笔记·学习·学习笔记
桦说编程8 小时前
深入解析CompletableFuture源码实现(2)———双源输入
java·后端·源码
java_t_t8 小时前
ZIP工具类
java·zip
lang201509288 小时前
Spring Boot优雅关闭全解析
java·spring boot·后端
pengzhuofan9 小时前
第10章 Maven
java·maven
百锦再10 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net