Search code examples
java-8comparator

How to check for null before comparing by linked object key using Comparator.comparing in java


Comparator.comparing(ProjectVo::getCategory, Comparator.comparing(ProjectCategoryVo::getName))

However category can be null and hence this is throwing exception when sorted

How can i apply null comparator for category?


Solution

  • You don't need to use naturalOrder to guard against getCategory returning null:

    Comparator.comparing(ProjectVo::getCategory,
        Comparator.nullsFirst(Comparator.comparing(ProjectCategoryVo::getName)));
    

    If I was worried about getName returning null I would use that trick:

    Comparator.comparing(ProjectVo::getCategory,
        Comparator.comparing(ProjectCategoryVo::getName,
            Comparator.nullsFirst(Comparator.naturalOrder())));
    

    If I was worried about a ProjectVo being null:

    Comparator.nullsFirst(Comparator.comparing(ProjectVo::getCategory,
            Comparator.comparing(ProjectCategoryVo::getName)));