Sort a Java collection object based on one field in it and apply checks

0 java list java-8 null-check

retList.sort((comp1, comp2) ->
         compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
        .get(comp1.getCompartment())));
Run Code Online (Sandbox Code Playgroud)

I want to add a null check before comparing. How can I do that?

retList.sort((comp1, comp2) ->
            if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
                compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
                .get(comp1.getCompartment()));
        );

//I want to do something like this
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 8

Your operation

retList.sort((comp1, comp2) ->
    compartmentOrderMap.get(comp2.getCompartment())
        .compareTo(compartmentOrderMap.get(comp1.getCompartment())));
Run Code Online (Sandbox Code Playgroud)

is equivalent to

retList.sort(Comparator.comparing(
    c -> compartmentOrderMap.get(c.getCompartment()), 
    Comparator.reverseOrder()));
Run Code Online (Sandbox Code Playgroud)

With this factory based form, you can easily replace the value comparator with a null safe variant, e.g.

retList.sort(Comparator.comparing(
    c -> compartmentOrderMap.get(c.getCompartment()),
    Comparator.nullsFirst(Comparator.reverseOrder())));
Run Code Online (Sandbox Code Playgroud)

You have to decide for a policy. Instead of nullsFirst you can also use nullsLast.