我有一个Stream
个字符串,并将每个字符串映射到Optional<String>
。由于我之后过滤了空Optionals
,因此返回的流应该只包含非空Optionals
来保存非空字符串。
为什么findFirst()
会抛出NullPointerException
?
Optional<String> cookie =
Stream.of(headers.get(HttpHeaders.SET_COOKIE), headers.get(HttpHeaders.COOKIE))
.flatMap(Collection::stream)
.filter(s -> s.contains("identifier"))
.map(this::parseCookieValue) //returns an Optional<String> from Optional.ofNullable(), null-values should result in empty Optionals
.filter(Optional::isPresent) // filters out non-present values
.map(Optional::get) // all Optionals here should have values
.findFirst(); // so why is this still throwing a NullPointerException?
堆栈跟踪:
Caused by: java.lang.NullPointerException
at com.example.services.impl.RestServiceImpl$$Lambda$11/873175411.apply(Unknown Source)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:267)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:529)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:516)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
at com.example.services.impl.RestServiceImpl.login(RestServiceImpl.java:81)
第81行是findFirst()
- 方法调用。
答案 0 :(得分:10)
读取Stream API中出现的异常并非易事。你不应该忘记的第一件事是Stream是懒惰的:一切都是在终端操作中实际执行的。因此,在您的情况下,整个Stream处理在findFirst
调用内执行,如果您看到NullPointerException
它可以由管道的任何步骤生成,而不仅仅由findFirst
本身生成。让我们仔细看看堆栈跟踪的顶部:
Caused by: java.lang.NullPointerException
at com.example.services.impl.RestServiceImpl$$Lambda$11/873175411.apply(Unknown Source)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:267)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
如果在跟踪中有一些Spliterator.tryAdvance
或Spliterator.forEachRemaining
调用,则在处理某些流元素期间实际发生了异常,而不是在最终操作期间。以下是实际将空值传递给findFirst
时异常的样子:
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Optional.<init>(Optional.java:96)
at java.util.Optional.of(Optional.java:108)
at java.util.stream.FindOps$FindSink$OfRef.get(FindOps.java:193)
at java.util.stream.FindOps$FindSink$OfRef.get(FindOps.java:190)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
看,这里没有spliterator调用:它完成了每个元素的处理并在此之后抛出。
您案例中最顶层的堆栈框架显示为com.example.services.impl.RestServiceImpl$$Lambda$11/873175411.apply
。自动生成的lambda中的NullPointerException
(未指向任何已知代码)通常意味着为null this
参数调用未绑定的方法引用。为了更清楚,你可以用lambda代替代码中的所有方法引用,因为它们实际上有一个源代码行:
Optional<String> cookie =
Stream.of(headers.get(HttpHeaders.SET_COOKIE), headers.get(HttpHeaders.COOKIE))
.flatMap(c -> c.stream())
.filter(s -> s.contains("identifier"))
.map(c -> this.parseCookieValue(c))
.filter(opt -> opt.isPresent())
.map(opt -> opt.get())
.findFirst();
现在,您将看到包含行号的附加框架:
Exception in thread "main" java.lang.NullPointerException
at com.example.services.impl.RestServiceImpl.lambda$0(RestServiceImpl.java:14)
at com.example.services.impl.RestServiceImpl$$Lambda$1/2055281021.apply(Unknown Source)
at java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:267)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
此行号完全指向显示您的例外原因的.flatMap(c -> c.stream())
行。
如果您不想将所有可疑的方法引用转换为lambdas,您可能会有一个线索查看前一帧(ReferencePipeline.java:267)。这一行在flatMap
实现中的JDK源appears中,因此您可以得出结论flatMap
步骤发生了错误。
总结一下:
tryAdvance
或forEachRemaining
spliterator方法调用。当您没有看到它时,每个元素处理可能已经完成或未开始。答案 1 :(得分:0)
我发现了错误,评论者是正确的:问题不是Optional
,而是源列表!如果找不到密钥,则HttpHeaders.get(Object key)会返回null
。我错误地假设某些null
- 列表未被收集,或者返回空列表而不是null
。如果我对此进行过滤(或者先检查标题是否存在),它会按预期工作。
感谢您指点我!我写了一个小例子,向所有感兴趣的人展示这个问题:
package com.example;
import java.util.*;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
succeeds();
fixed();
fails();
}
private static void succeeds() {
List<String> list1 = Collections.singletonList("identifier=xxx");
List<String> list2 = Collections.emptyList();
Optional<String> cookieValue =
Stream.of(list1, list2)
.flatMap(Collection::stream)
.filter(s -> s.contains("identifier"))
.map(Main::parseCookieValue)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
System.out.println(cookieValue.orElse("Code works as expected with non-null Lists"));
}
private static void fails() {
List<String> list1 = Collections.singletonList("identifier=xxx");
List<String> list2 = null;
Optional<String> cookieValue =
Stream.of(list1, list2)
.flatMap(Collection::stream)
.filter(s -> s.contains("identifier"))
.map(Main::parseCookieValue)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
System.out.println(cookieValue.orElse("Exception thrown prior to this call!"));
}
private static void fixed() {
List<String> list1 = Collections.singletonList("identifier=xxx");
List<String> list2 = null;
Optional<String> cookieValue =
Stream.of(list1, list2)
.filter(l -> l != null)
.flatMap(Collection::stream)
.filter(s -> s.contains("identifier"))
.map(Main::parseCookieValue)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
System.out.println(cookieValue.orElse("Code works as expected after null Lists have been filtered"));
}
private static Optional<String> parseCookieValue(final String headerString) {
System.out.println("Parsing method called");
//return an empty Optional for testing;
return Optional.empty();
}
}