基於使用Java 8的一些參數來過濾此列表。可是若是參數是null,則拋出NullPointerException。如何過濾掉空值ide
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