简介
经常我们都会对List集合中的元素进行操作,并且List集合允许存储相同的值,不像Map会对重复元素进行覆盖,可能我们会使用for循环进行遍历集合在判断元素是否相等,我们我们可以使用集合中的
stream流中的filter过滤
相等的值
演示
实体类:
//使用插件后可以不创建toString/set/get方法
@Data
class People{
//姓名
String name;
//地址
String addres;
//年龄
Integer age;
}
main方法:
创建peopleList集合,并且
存入对象1号
,对象2号
.并且现在需求是需要对peopleList 集合中
对某个属性进行判断是否存在
.创建需要验证的对象,
public static void main(String[] args) {
List<People> peopleList=new ArrayList<>();
//对象1号
People people=new People();
people.setName("itmei");
people.setAge(18);
people.setAddres("福建");
peopleList.add(people);
//对象2号
People people2=new People();
people2.setName("小东东");
people2.setAge(10);
people2.setAddres("北京");
peopleList.add(people2);
//需要对peopleList 集合中对 某个属性进行判断是否存在 ,
//判断现有的name是否存在集合中,如果不存在就添加,反之就添加到集合中
//验证的对象
People verifyPeople=new People();
verifyPeople.setName("itmei");
verifyPeople.setAddres("mmm");
//核心代码
boolean flag=peopleList.stream().filter(item->{
//判断现有的name是否存在集合中
return item.getName().equals(verifyPeople.getName());
}).findAny().isPresent();
//对返回结果进行逻辑处理
if (flag){
System.out.println("已存在");
}else {
System.out.println("不存在,则添加");
peopleList.add(verifyPeople);
}
System.out.println("集合中的元素"+peopleList.toString());
}
结果
可以看出因为集合中的name没有重复所以允许添加到
peopleList
集合中
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/83821.html