comparator with null values

前端 未结 9 1171
萌比男神i
萌比男神i 2020-12-04 16:25

We have some code which sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.

How

9条回答
  •  甜味超标
    2020-12-04 16:46

    If you are using Java 8, you have 2 new static methods in the Comparator class, which come in handy:

    public static  Comparator nullsFirst(Comparator comparator)
    public static  Comparator nullsLast(Comparator comparator)
    

    The comparison will be null safe and you can choose where to place the null values in the sorted sequence.

    The following example:

    List monkeyBusiness = Arrays.asList("Chimp", "eat", "sleep", "", null, "banana",
                "throw banana peel", null, "smile", "run");
    Comparator comparator = (a, b) -> a.compareTo(b);
    monkeyBusiness.stream().sorted(Comparator.nullsFirst(comparator))
                .forEach(x -> System.out.print("[" + x + "] "));
    

    will print: [null] [null] [] [Chimp] [banana] [eat] [run] [sleep] [smile] [throw banana peel]

提交回复
热议问题