Java8中使用lambda不为null时才过滤值
作者:互联网
基于使用Java 8的一些参数来过滤此列表。但是如果参数是null,则抛出NullPointerException。如何过滤掉空值
List<String> carsFiltered = Optional.ofNullable(cars)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull) //filtering car object that are null
.map(Car::getName) //now it's a stream of Strings
.filter(Objects::nonNull) //filtering null in Strings
.filter(name -> name.startsWith("M"))
.collect(Collectors.toList()); //back to List of Strings
标签:filtering,stream,时才,Java8,filter,过滤,null,Strings 来源: https://blog.51cto.com/1929297/2603621