处理空指针并在流中抛出异常 [英] Handling null pointers and throwing exceptions in streams

查看:22
本文介绍了处理空指针并在流中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个 Parent 类,它只包含一个 Integer 属性.我创建了 6 个父类对象和一个空变量.然后我将这些对象添加到列表中.

Let's consider a Parent class which contains only one Integer attribute. I created 6 objects of parent class and with one null variable. Then I added these objects to a list.

我想通过Integer属性的值来检索对应的对象.我为此使用了 Java 8 Streams.

I want to retrieve the corresponding object by the value of Integer attribute. I used Java 8 Streams for it.

Predicate<Parent> predicate = e -> e.getId() == 100; // sample attribute value
result = list.stream().filter(predicate).collect(Collectors.toList());

但是我得到了NullPointerException,所以我编辑了代码:

But I got NullPointerException, so I edited the code:

list.stream().filter(h -> h!=null).filter(predicate).collect(Collectors.toList());

但如果任何对象为空,我想抛出异常.如果列表中没有对象为空,那么我想从列表中检索相应的对象.

But I want to throw an exception if any of the object is null. If no objects in the list is null, then I want to retrieve the corresponding object from list.

如何使用 Java 8 Streams 使用单个语句实现此目的?

How can I achieve this using a single statement using Java 8 Streams?

推荐答案

JB Nizet 的回答是可以的,但是它使用 map 只是为了它的副作用而不是用于映射操作,这是一种奇怪的.当您只对某些事情的副作用感兴趣时,可以使用一种方法,例如抛出异常:peek.

JB Nizet answer is okay, but it uses map only for its side effects and not for the mapping operation, which is kind of weird. There is a method which can be used when you are solely interested in the side effects of something, such as throwing an exception: peek.

List<Parent> filtered = list.stream()
    .peek(Objects::requireNonNull)
    .filter(predicate)
    .collect(Collectors.toList());

如果你想要自己的异常,只需在那里放一个 lambda:

And if you want your own exception just put a lambda in there:

List<Parent> filtered = list.stream()
    .peek(p -> { if (p == null) throw new MyException(); })
    .filter(predicate)
    .collect(Collectors.toList());


检查异常

如果您的异常被检查,您可以事先检查空值,如果您不介意遍历列表两次.这对您来说可能是最好的,但可能并不总是可行.


Checked Exceptions

If your exception is checked you can either check for null beforehand, if you don't mind traversing the list twice. This is probably best in your case, but might not always be possible.

if (list.contains(null)) throw new MyCheckedException();

你也可以在你的流管道中抛出一个未经检查的异常,捕捉它然后抛出已检查的异常:

You could also throw an unchecked exception in your stream pipeline, catch it and then throw the checked one:

try {
    ...
        .peek(p -> { if (p == null) throw new MyException(); })
    ...
} catch (MyException exc) {
    throw new MyCheckedException();
}


偷偷投掷

或者你可以走优雅但有争议的道路,并使用偷偷摸摸的方法.

但要小心!这种技术绕过了检查异常系统,您应该知道自己在做什么.一定要声明周围的方法抛出MyCheckedException!如果你不这样做,编译器不会警告你,而且如果检查异常出现在它们不期望的地方,它可能会导致奇怪的错误.

But beware! This technique circumvents the checked exception system and you should know what you are doing. Be sure to declare that the surrounding method throws MyCheckedException! The compiler won't warn you if you don't, and it will likely cause weird bugs if checked exceptions appear where they are not expected.

@SuppressWarnings("unchecked")
public <T extends Throwable> void throwSneakily(Throwable t) throws T {
    throw (T) t;
}

public void m() throws MyCheckedException {
    List<Parent> filtered = list.stream()
        .peek(p -> { if (p == null) throwSneakily(new MyCheckedException()); })
        .filter(predicate)
        .collect(Collectors.toList());
}

这篇关于处理空指针并在流中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆