NullsFirst() and nullsLast() in java comparator

Generally, we can write like this for the List<Map<XX,XX>> type sorting

Sort Score:

List<Map<String, Object>> resultlist = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("id", "1");
        map1.put("name", "张三");
        map1.put("Score", 86.5);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id", "2");
        map2.put("name", "李四");
        map2.put("Score", 90.0);
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("id", "3");
        map3.put("name", "王五");
        map3.put("Score", 70.5);

        resultlist.add(map1);
        resultlist.add(map2);
        resultlist.add(map3);

 //升序        
resultlist.sort(Comparator.comparing((Map<String, Object> m) -> ((Double) m.get("Score")))); 

//降序
//resultlist.sort(Comparator.comparing((Map<String, Object> m) -> ((Double) m.get("Score"))).reversed()); 

But at this time, if Wang Wu's Score is null, the sort operation on name will report an error.
At this point, you can use nullsFirst() or nullsLast() to handle nulls.

nullsFirst():

This method returns the comparator, which is a null comparison, and considers that a null value is less than a non-null. Null is first operated by the following logic:
1. The null element is considered less than non-null (that is, the value of null is less than non-null).
2. When two elements are empty, they are considered equal.
3. When the two elements are not empty, the specified Comparator determines the order.
4. If the specified comparator is null, the returned comparator treats all non-null elements as equal.
5. If the specified comparator is serializable, the returned comparator can be serialized.

nullsLast () :

The method returns the comparator, which is a null comparison, and considers a larger null value than non-null. Null is first operated by the following logic:
1. The null element is considered to be greater than non-null.
2. When two elements are empty, they are considered equal.
3. When the two elements are not empty, the specified Comparator determines the order.
4. If the specified comparator is null, the returned comparator treats all non-null elements as equal.
5. If the specified comparator is serializable, the returned comparator can be serialized.

Therefore, the above sort can be written like this to avoid null pointer exceptions:

//升序
resultlist.sort(Comparator.comparing((Map<String, Object> m) -> ((Double)m.get("Score")),Comparator.nullsLast(Comparator.naturalOrder())));

//降序
resultlist.sort(Comparator.comparing((Map<String, Object> m) -> ((Double)m.get("Score")),Comparator.nullsLast(Comparator.reverseOrder())));   

Guess you like

Origin blog.csdn.net/qq_33697094/article/details/108777551