Attempting to use Comparator to sort by name, ignore case, as well as nulls first

走远了吗. 提交于 2019-12-05 17:18:08

There are two types of nulls you can have in your list. You can have null Person references, and you can have Persons with null names.

In the first case, you have to apply nullsFirst to the base comparator you want to use:

comparator = Comparator.nullsFirst(
        Comparator.comparing(Person::getName, String.CASE_INSENSITIVE_ORDER));

If you have the possibility of null names, you need to make sure that your key never returns a null, or that you apply nullsFirst to String.CASE_INSENSITIVE_ORDER. The second option is of course much easier:

comparator = Comparator.comparing(
        Person::getName, Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER));

If you have both options (null references and null names), you will have to combine both versions and apply nullsFirst twice:

comparator = Comparator.nullsFirst(
        Comparator.comparing(
                Person::getName,
                Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER)
        )
);

If you are chaining multiple comparisons like this, the outer nullsFirst, which ensures that null Persons get sorted properly, can be applied to the entire chain:

comparator = Comparator.nullsFirst(
        Comparator.comparing(
                Person::getName,
                Comparator.nullsFirst(String.CASE_INSENSITIVE_ORDER)
        ).thenComparing(...)
);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!