Search code examples
javalistjava-8null-check

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


retList.sort((comp1, comp2) ->
         compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
        .get(comp1.getCompartment())));

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

Solution

  • you have to put {} inside the lambda for multiple line code:

    retList.sort((comp1, comp2) -> {
                if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
                    return compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
                    .get(comp1.getCompartment()));
                else 
                   // throw a RuntimeException or return some integer value based on your logic
            });