使用Java的空第一方法获取以下例外8
问题描述:
我有下面的程序,我试图在其中打印null
。我正在使用Java 8。下面是我的代码来实现它:使用Java的空第一方法获取以下例外8
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", "[email protected]", Gender.FEMALE, 15));
personList.add(new Person("Bob", "[email protected]", Gender.MALE, 16));
personList.add(new Person("Eric", "[email protected]", Gender.MALE, 17));
personList.add(new Person("Carol", "[email protected]", Gender.FEMALE, 23));
personList.add(new Person(null, "[email protected]", Gender.FEMALE, 15));
personList.add(new Person("Carol", "[email protected]", Gender.FEMALE, 23));
personList.add(new Person("David", "[email protected]", Gender.MALE, 19));
personList.add(new Person("Bob", "[email protected]", Gender.MALE, 16));
现在下面是我写的,首先打印null
名称代码:
personList.stream().sorted(Comparator.nullsFirst(Comparator.comparing(Person::getName))).forEach(System.out::println);
,但我得到了下面的异常,请告知如何克服这一点?
Exception in thread "main" java.lang.NullPointerException
at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
at java.util.Comparators$NullComparator.compare(Comparators.java:83)
at java.util.TimSort.binarySort(TimSort.java:296)
at java.util.TimSort.sort(TimSort.java:221)
答
的NPE是传递一个null
值Comparator.comparing
的Javadoc的结果表示
抛出:NullPointerException - 如果参数为null
也许你可以试试
Comparator.comparing(Person::getName, Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER))
将会产生
null
Alice
Bob
Bob
Carol
Carol
David
Eric
答
这是因为你使用的比较是错误的。看到这个,并应该工作
import java.util.stream.*;
import static java.util.Comparator.*;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", "[email protected]"));
personList.add(new Person("Bob", "[email protected]"));
personList.add(new Person("Eric", "[email protected]"));
personList.add(new Person("Carol", "[email protected]"));
personList.add(new Person(null, "[email protected]"));
personList.add(new Person("Carol", "[email protected]"));
personList.add(new Person("David", "[email protected]"));
personList.add(new Person("Bob", "[email protected]"));
System.out.println(personList);
personList.stream().sorted(comparing(Person::getName, nullsFirst(naturalOrder()))).forEach(System.out::println);
}
}
class Person
{
private String name,email;
Person(String name, String email)
{
this.name=name;
}
public String getName()
{
return name;
}
public String toString(){return name;}
}
'forEach(System.out :: println)'是那里可能的原因。 – nullpointer
阅读https://stackoverflow.com/questions/26350996/java-8-comparator-nullsfirst-naturalorder-confused –