我有:
List<Optional<MyObject>> myList;
通过从文件中读取来填充此列表。文件读取完成后,我将对空列表进行检查:
if(myList.size() == 0){//}
然后执行以下操作:
myList.stream()
.filter(Optional::isPresent)
.map(i → i.orElse(new MyObject(“adventureBook”, 20))
.collect(groupingBy(MyObject::getBookType, TreeMap::new, mapping(MyObject::getBookPrice, toList())));
我大约要读取350k MyObject文件,可以正常读取300k文件,但是当我尝试读取整批c.350k文件时,它将在collect()上引发空指针异常。
尽管包装了Optional <>并检查了Optional :: isPresent,Optional :: orElse等,仍然有一个空对象设法偷偷溜走并且鉴于我有这么多文件的可能性,这是最好的方法尝试缩小错误文件的范围?谢谢
编辑:已添加堆栈跟踪
Exception in thread "main" java.lang.NullPointerException
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
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.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.mypackage.MyObject.main(MyObject.java:108)
答案 0 :(得分:2)
在非null MyObject
为null的情况下,属性之一可能是?您确实在做filter(Optional::isPresent)
,但这并不意味着字段本身不为空。 MyObject::getBookType
或MyObject::getBookPrice
仍然很容易为空。
答案 1 :(得分:-1)
关于“尝试缩小错误文件的最佳方法是什么?”的问题,我通常在解析时使用以下模式:
for (File file : filesToParse) {
try {
parseFile(file);
} catch (IOException e) {
// rethrow the exception, and make sure that
// 1. you give the file in the message, to help narrow the error down
// 2. pass the original exception as 2nd parameter, to preserve the stack trace
throw new IOException("Failed to parse file: " + file, e);
}
}