判断map的value是否包含某值,判断list中是否包含某值(基础向)

本文介绍了Java新手在处理Map和List时,如何使用更简洁的方法检查value是否存在或特定属性匹配,如`containsValue()`和`stream().anyMatch()`等高级API。

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

         对于一些Java新手,想要知道一个map中的value是否包含某值,或者list中是否包含某值,可能会选择遍历,比如:

Map<String, Object> map = new HashMap<>();
map.put("1", 1);
map.put("2", '2');
map.put("3", true);
map.put("4", 1.4);
map.put("5", "no");
boolean isContainValue = false;
for (String s : map.keySet()) {
    if (map.get(s).equals(1.4)) {
        isContainValue = true;
        break;
    }
}
System.out.println(isContainValue);

或者:

List<Student> list = new ArrayList<>();
list.add(new Student("小明", 18));
list.add(new Student("小刚", 20));
list.add(new Student("小霞", 19));
list.add(new Student("小智", 21));
boolean isContainProperty = false;
for (Student student : list) {
    if ("小明".equals(student.getName())) {
        isContainProperty = true;
        break;
    }
}
System.out.println(isContainProperty);

但其实,可以这样:

boolean isContainValue = map.containsValue(1.4);

以及:

boolean isContainProperty = list.stream().anyMatch(o -> "小明".equals(o.getName()));

当然,这是存在,如要想要不存在或者任意,可以把anyMatch换成noneMatch或者allMatch。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值