Concept
How can a Java Comparator handle null values?
ComputerScienceOne / Importance of javaequals() and javahashCode() Methods
"Other considerations include null values. How we handle these is a design decision. We could ignore it, in which case such elements would likely result in a NullPointerException and expect the user to prevent or handle such instances. This may be the preferable choice in most instances, in fact. Alternatively, we could handle null objects in the design of our Comparator. Code Sample 36.3 presents a Comparator for our Student class that orders null instances first.\n\n1 Comparator<Student> byNameWithNulls = new Comparator<Student>() {\n\n2 @Override\n\n3 public int compare(Student a, Student b) {\n\n4 if(a == null && b == null) {\n\n5 return 0;\n\n6 } else if(a == null && b != null) {\n\n7 return -1;\n\n8 } else if(a != null && b == null) {\n\n9 return 1;\n\n10 } else {\n\n11 if(a.getLastName().equals(b.getLastName())) {\n\n12 return a.getFirstName().compareTo(b.getFirstName());\n\n13 } else {\n\n14 return a.getLastName().compareTo(b.getLastName());\n\n15 }\n\n16 }\n\n17 }\n\n18 };\n\nCode Sample 36.3.: Handling Null Values in Java Comparators\n\nThis solution only handles null Student values, not null values within the Student object. If the getters used in the Comparator return null values, then we could still have NullPointerExceptions."
Related Ideas
- How can method references and Comparator methods make ordering more concise?ComputerScienceOne · Java 8: Lambda Expressions
- What should you consider when sorting collections or arrays with null values?ComputerScienceOne · Handling javanull values
- How can anonymous classes define custom Java comparators?ComputerScienceOne · Comparators
- How should a Comparator order elements in a SortedSet?ComputerScienceOne · Handling javanull values
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How can Comparator order Student objects by different fields?ComputerScienceOne · Comparators
- How can lambda expressions build a multi-field Comparator?ComputerScienceOne · Java 8: Lambda Expressions
- How does Java sort arrays and lists with comparators?ComputerScienceOne · Sorted Collections