Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何避免收集器出现NPE.SummaringIT_Java_Collections_Java Stream - Fatal编程技术网

Java 如何避免收集器出现NPE.SummaringIT

Java 如何避免收集器出现NPE.SummaringIT,java,collections,java-stream,Java,Collections,Java Stream,我们的代码需要从对象列表中返回max和min值,这与下面的代码非常相似: import java.util.IntSummaryStatistics; import java.util.List; import java.util.stream.Collectors; public class Test { private Short attr; public Short getAttr() { return attr; } public

我们的代码需要从对象列表中返回max和min值,这与下面的代码非常相似:

import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

    private Short attr;

    public Short getAttr() {
        return attr;
    }

    public static void main (String[] args) {
        List<Test> tests = List.of(new Test(), new Test());

        IntSummaryStatistics i = tests.stream()
                .map(Test::getAttr)
                .map(Integer::valueOf)
                .filter(in -> in != null && in > 0)
                .collect(Collectors.summarizingInt(Integer::intValue));

        System.out.println(i.getMax() + " " + i.getMin());
    }

}
NPE被扔进去了

   .map(Integer::valueOf)
as将取消对输入的装箱并导致NPE。 为了解决这个问题,我建议以下方法之一

建议由Holger删除。mapInteger::valueOf并在收集器内将Short映射到int Short::intValue。摘要如下: 请注意,和将分别为Integer.MIN_值和Integer.MAX_值,这不直观!!当流为空时。 因此,输出将为-2147483648 2147483647

为attr提供默认值,可能为0。 NPE被扔进去了

   .map(Integer::valueOf)
as将取消对输入的装箱并导致NPE。 为了解决这个问题,我建议以下方法之一

建议由Holger删除。mapInteger::valueOf并在收集器内将Short映射到int Short::intValue。摘要如下: 请注意,和将分别为Integer.MIN_值和Integer.MAX_值,这不直观!!当流为空时。 因此,输出将为-2147483648 2147483647

为attr提供默认值,可能为0。
您应该在调用“.mapInteger::valueOf”之前进行筛选,或者只删除.mapInteger::valueOf”并将终端操作更改为collectCollectors。SummaringIntShort::IntValues您应该在调用“.mapInteger::valueOf”之前进行筛选,或者只删除.mapInteger::valueOf并将终端操作更改为collectCollectors.SummaringIntShort::intValue
IntSummaryStatistics i = tests.stream()
                .map(Test::getAttr)
                .filter(in -> in != null && in > 0)
                .collect(Collectors.summarizingInt(Short::intValue));