如果其中一个对象在 Java 中具有空值,则带映射的过滤器会抛出空指针异常

filter with map throws null pointer exception if one of the object has null values in Java

我正在尝试迭代我的地图并使用此方法过滤掉它的列表,但如果我没有可用的值 属性(id)它在 Java.

中抛出空指针异常

如果 ID 与给定代码匹配,我如何以迭代哈希图并过滤掉值的方式进行过滤?

data.entrySet().stream()
       .filter(a -> a.getValue().stream()
           .anyMatch(l->l.id.equals(code)))
        .collect(Collectors.toMap(
             e -> e.getKey(),
             e -> e.getValue()));

堆栈跟踪:

java.lang.NullPointerException

首先,您应该在验证代码之前添加空值检查。其次,使用 Objects::equals 可能更好,因为它是空安全的:

data.entrySet()
    .stream()
    .filter(e -> Objects.nonNull(e.getValue())
        && e.getValue().stream().anyMatch(l -> Objects.equals(code, l.id))
    )
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue
    ));