JAVA 日常遇到问题收集

Stream中过滤null的情形

class Customer {

	private Long id;
	private String name;

	public Customer(Long id, String name) {
		this.id = id;
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
		List<Customer> customerList = new ArrayList<>();
		customerList.add(new Customer(1L, "Ryu"));
		customerList.add(new Customer(2L, "Ken"));
		customerList.add(new Customer(3L, null));

		customerList.add(new Customer(5L, null));
		customerList.add(new Customer(null, "Zangief"));

要求查询出id不是5的列表数据:

普通写法:

List<Customer> customers = customerList.stream().filter(x ->5L!=x.getId()).collect(Collectors.toList());

这个语句会抛出异常,因为列表中有一条数据id为null

但是如果过滤的是Name,String类型的就没有问题。

测验数字与null对比:

		int a=1;
		Integer aa=null;
		Integer bb=1;
		//System.out.println(aa.equals(a)); //aa为null,error
		//System.out.println(aa == a); //aa为null,error
		//System.out.println(a == aa);//aa为null,error
		System.out.println(bb.equals(aa));
		System.out.println(bb == aa);
		System.out.println(aa==bb);

当aa=1,这个时候没有任何问题

但是当aa=null,上面3种方式都会抛出异常, java.lang.NullPointerException

结果

经过这样的判断,上述的filter代码可以优化为:

List<Customer> customers = customerList.stream().filter(x ->!Long.valueOf(5L).equals(x.getId())).collect(Collectors.toList());

所以遇到基本数据类型,最好还是转换成类型处理

posted @   hongdada  阅读(232)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2018-05-28 SpringBoot 全局统一记录日志
点击右上角即可分享
微信分享提示