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());

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

猜你喜欢

转载自www.cnblogs.com/hongdada/p/12982254.html