Why does findFirst() throw a NullPointerException if the first element it finds is null?

后端 未结 5 913
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 08:39

Why does this throw a java.lang.NullPointerException?

List strings = new ArrayList<>();
        strings.add(null);
        s         


        
5条回答
  •  無奈伤痛
    2020-11-28 08:59

    The following code replaces findFirst() with limit(1) and replaces orElse() with reduce():

    String firstString = strings.
       stream().
       limit(1).
       reduce("StringWhenListIsEmpty", (first, second) -> second);
    

    limit() allows only 1 element to reach reduce. The BinaryOperator passed to reduce returns that 1 element or else "StringWhenListIsEmpty" if no elements reach the reduce.

    The beauty of this solution is that Optional isn't allocated and the BinaryOperator lambda isn't going to allocate anything.

提交回复
热议问题