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

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

  • 相关阅读:
    浏览器 窗口 scrollTop 的兼容性问题
    document.documentElement.scrollTop || document.body.scrollTop;
    javascript函数querySelector
    :before和:after的内幕以及伪类
    css伪类伪元素
    JavaScript 运动框架 Step by step
    js中style,currentStyle和getComputedStyle的区别
    js函数变量
    函数
    oracle语法练习
  • 原文地址:https://www.cnblogs.com/hongdada/p/12982254.html
Copyright © 2011-2022 走看看