mapToLong报空指针异常

mapToLong报空指针异常

Exception in thread "main" java.lang.NullPointerException
	at test.collection.TestAuto.lambda$null$0(TestAuto.java:12)
	at java.util.stream.ReferencePipeline$5$1.accept(ReferencePipeline.java:227)
	at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.LongPipeline.reduce(LongPipeline.java:438)
	at java.util.stream.LongPipeline.sum(LongPipeline.java:396)
	at test.collection.TestAuto.lambda$main$1(TestAuto.java:12)
	at test.collection.TestAuto.main(TestAuto.java:13)

Process finished with exit code 1

解决

Stream.of(msgs).mapToLong(s -> Objects.isNull(s) ? 0L : s).sum()

示例代码

package test.collection;

import java.util.Objects;
import java.util.stream.Stream;

public class TestAuto {
     
    interface Fun2 {
     
        void sum(Long... msgs);
    }

    public static void main(String[] args) {
     
        Fun2 fun2 = msgs -> System.out.println(Stream.of(msgs).mapToLong(s -> Objects.isNull(s) ? 0L : s).sum());
        fun2.sum(1L, 2L, 3L, 4L, 999L, null);
    }
}

你可能感兴趣的:(Java,java,stream,bug,jdk)