如何判断list map集合中是否存在某个元素

本文介绍了在Java中如何使用list和map集合进行元素判断与去重的实用技巧,包括使用contains方法检查元素是否存在,以及利用hashMap实现去重操作。
该文章已生成可运行项目,

1.在list中判断是是否存在相同元素。
用list的 contains(Object o) 方法
JDKAPI  contains

2.list集合中去重

代码:

public static void main(String[] args) {
			
			Student stu1 = new Student("张三", 5);
			Student stu2 = new Student("李四", 5);
			Student stu3 = new Student("王五", 5);
			
			List<Student> stuList = new ArrayList<Student>();
			List<Student> stuList2 = new ArrayList<Student>();
			stuList.add(stu1);
			stuList.add(stu2);
			stuList.add(stu1);
			for(int i=0;i<stuList.size();i++){
				//不包含则加入
				if(!stuList2.contains(stuList.get(i))){
					stuList2.add(stuList.get(i));
				}
			}
			System.out.println(stuList.contains(stu1));
			System.out.println(stuList.contains(stu3));
			System.out.println(stuList);
			System.out.println(stuList2);
			
		}

结果:

在这里插入图片描述

3.Map集合是否包含指定的Key和Value containsKey() containsValue()
在Map中,用containsKey()方法,判断是否包含某个Key值;用containsValue()方法,判断是否包含某个Value值。

JDK API containsKey

JDKAPI containsValue
举个例子

public static void main(String[] args) {

		Student stu1 = new Student("张三", 5);
		Student stu2 = new Student("李四", 5);
		Student stu3 = new Student("王五", 5);
		
		Map<String,Student> result = new HashMap<String, Student>();
		result.put("1", stu1);
		result.put("3", stu2);
		
		System.out.println(result.containsKey("1"));
		System.out.println(result.containsKey("2"));
		System.out.println(result.containsValue(stu1));
		System.out.println(result.containsValue(stu3));
	}
	

结果:
在这里插入图片描述

本文章已经生成可运行项目
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值