我有以下程序,我正在尝试打印null
。我正在使用Java 8。以下是我实现它的代码:
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", "alice@gmail.com", Gender.FEMALE, 15));
personList.add(new Person("Bob", "bob@gmail.com", Gender.MALE, 16));
personList.add(new Person("Eric", "eric@gmail.com", Gender.MALE, 17));
personList.add(new Person("Carol", "carol@gmail.com", Gender.FEMALE, 23));
personList.add(new Person(null, "alice@gmail.com", Gender.FEMALE, 15));
personList.add(new Person("Carol", "carol@gmail.com", Gender.FEMALE, 23));
personList.add(new Person("David", "david@gmail.com", Gender.MALE, 19));
personList.add(new Person("Bob", "bob@gmail.com", 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)
答案 0 :(得分:2)
这是因为您使用比较器错误。看到这个并且可以工作
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", "alice@gmail.com"));
personList.add(new Person("Bob", "bob@gmail.com"));
personList.add(new Person("Eric", "eric@gmail.com"));
personList.add(new Person("Carol", "carol@gmail.com"));
personList.add(new Person(null, "alice@gmail.com"));
personList.add(new Person("Carol", "carol@gmail.com"));
personList.add(new Person("David", "david@gmail.com"));
personList.add(new Person("Bob", "bob@gmail.com"));
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;}
}
答案 1 :(得分:1)
NPE是将null
值传递给Comparator.comparing
Javadoc说
如果参数为null,则@throws NullPointerException
也许尝试像
这样的东西Comparator.comparing(Person::getName, Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER))
哪个产生
null
Alice
Bob
Bob
Carol
Carol
David
Eric