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

Time:07-28

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

CodePudding user response:

Your operation

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

is equivalent to

retList.sort(Comparator.comparing(
    c -> compartmentOrderMap.get(c.getCompartment()), 
    Comparator.reverseOrder()));

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())));

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

CodePudding user response:

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
        });

CodePudding user response:

Use if/then/else to specify your needs. If you want all of this within one line, check the ternary operator on https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

It is explained including some examples here: https://www.tutorialspoint.com/Java-Ternary-Operator-Examples

  • Related