This may be a simple question, but I would like to clearly understand it ...
I have a code like this:
public final class Persona { private final int id; private final String name public Persona(final int id,final String name) { this.id = id; this.name = name; } public int getId(){return id;} public String getName(){return name;} @Override public String toString(){return "Persona{" + "id=" + id + ", name=" + name+'}';} }
And I am testing this code:
import static java.util.Comparator.*; private void nullsFirstTesting() { final Comparator<Persona>comparator = comparing(Persona::getName,nullsFirst(naturalOrder())); final List<Persona>persons = Arrays.asList(new Persona(1,"Cristian"),new Persona(2,"Guadalupe"),new Persona(3,"Cristina"),new Persona(4,"Chinga"),new Persona(5,null)); persons .stream() .sorted(comparator) .forEach(System.out::println); }
This shows the following results:
Persona{id=5, name=null} Persona{id=4, name=Chinga} Persona{id=1, name=Cristian} Persona{id=3, name=Cristina} Persona{id=2, name=Guadalupe}
These results are okay with me, but I have a problem with understanding.
When I ignore the new Persona(5,null) object and pass the comparator:
final Comparator<Persona>comparator = comparing(Persona::getName);
It works like a charm. My sorting is natural order of name property . The problem arises when I add an object with name=null , I just thought that I needed my comparator like this.
final Comparator<Persona>comparator = comparing(Persona::getName,nullsFirst());
My thought was wrong : "OK, when the name is not null, they are sorted in the natural order of name , like the previous comparator, and if they are null , they will be the first , but my non-zero names will still be sorted in natural order .
But the correct code is this:
final Comparator<Persona>comparator = comparing(Persona::getName,nullsFirst(naturalOrder()));
I do not understand the nullsFirst parameter. I just thought that the natural order of name explicitly [by default] even handles null values.
But the docs say:
Returns a null-friendly comparator that considers null less than null. When both are null , they are considered equal. If both values are not equal to zero, the specified Comparator to determine the order. If the specified comparator is null , then the returned comparator considers all non-zero values equal.
This line: "If both values are non-zero, the specified Comparator used to determine the order.
I am confused when and how the natural order should be explicitly established or when they are deduced.