List集合去重

本文介绍了三种在Java中去除List集合中重复元素的方法:使用TreeSet结合Comparator、使用HashSet和使用HashMap。通过示例代码详细展示了如何根据特定字段 stuName 去重,并返回新的不包含重复项的List。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

List集合去重,去除重复字段

public class ListDistinctUtils {
 
	/**
	 * 使用TreeSet结合Comparator比较器实现List<Student>中stuName字段去重 </br>
	 * 
	 * @author weixiaohuai
	 * @modify_by weixiaohuai
	 * @param oldList
	 * @return
	 */
	public static <T extends Student> List<T> distinctBySet01(List<T> oldList) {
		Set<T> set = new TreeSet<>(new Comparator<T>() {
 
			@Override
			public int compare(T o1, T o2) {
				/**
				 * compareTo : 两个相同数据类型的比较,两个不同类型的数据不能用此方法来比较 <br/>
				 * 如果指定的数与参数相等返回: 0 <br/>
				 * 如果指定的数小于参数返回 : -1 <br/>
				 * 如果指定的数大于参数返回 : 1 <br/>
				 */
				return o1.getStuName().compareTo(o2.getStuName());
			}
		});
		set.addAll(oldList);
		return new ArrayList<>(set);
	}
 
	/**
	 * 使用Set实现List<Student>中stuName字段去重 </br>
	 * 
	 * @author weixiaohuai
	 * @modify_by weixiaohuai
	 * @param oldList
	 * @return
	 */
	public static <T extends Student> List<T> distinctBySet02(List<T> oldList) {
		Set<String> set = new HashSet<>();
		List<T> newList = new ArrayList<>();
		for (T t : oldList) {
			if (!set.contains(t.getStuName())) {
				set.add(t.getStuName());
				newList.add(t);
			}
		}
		return newList;
	}
 
	/**
	 * 使用Map实现List<Student>中stuName字段去重</br>
	 * 
	 * @author weixiaohuai
	 * @modify_by weixiaohuai
	 * @param oldList
	 * @return
	 */
	public static <T extends Student> List<T> distinctByMap(List<T> oldList) {
		Map<String, Object> existMap = new HashMap<String, Object>();
		List<T> newList = new ArrayList<>();
		for (T t : oldList) {
			String name = null != existMap.get(t.getStuName()) ? existMap.get(t.getStuName()).toString() : "";
			// 如果name为空表示不存在
			if (StringUtils.isBlank(name)) {
				existMap.put(t.getStuName(), t.getStuName());
				newList.add(t);
			}
		}
		return newList;
	}
 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值