zoukankan      html  css  js  c++  java
  • 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());
    

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

  • 相关阅读:
    截取图片组件
    node之mongodb的DAO
    模块化开发插件,组件
    tweenMax实体抛物线
    defineProperties属性的运用==数据绑定
    程序概述
    JavaBase
    [luogu 1092] 虫食算 (暴力搜索剪枝)
    [luogu1073 Noip2009] 最优贸易 (dp || SPFA+分层图)
    [51Nod 1218] 最长递增子序列 V2 (LIS)
  • 原文地址:https://www.cnblogs.com/hongdada/p/12982254.html
Copyright © 2011-2022 走看看