How to handle nulls when using Java collection sort

后端 未结 6 2103
离开以前
离开以前 2020-12-29 19:39

When using Collection.sort in Java what should I return when one of the inner objects is null

Example:

Collections.sort(list, new Comparator

        
6条回答
  •  执笔经年
    2020-12-29 20:27

    Following the answer from Nikita Rybak, i'm already have a enum comparator, and only add the null logic from here.

    public enum Orden implements Comparator {
            ByStrDescripcion {
                public int compare(CmunParametrosDTO item1, CmunParametrosDTO item2) {
                    if (item1.getStrDescripcion() == null && item2.getStrDescripcion() == null)
                        return 0;
                    if (item1.getStrDescripcion() == null)
                        return 1;
                    else if (item2.getStrDescripcion() == null)
                        return -1;
                    return item1.getStrDescripcion().compareTo(item2.getStrDescripcion());
                }
            }
            public abstract int compare(CmunParametrosDTO item1, CmunParametrosDTO item2);
    
            public Comparator ascending() {
                return this;
            }
    
            public Comparator descending() {
                return Collections.reverseOrder(this);
            }
    }
    

    In this form i can call the sort method on my list.

        if(isBolOrdAscendente()) Collections.sort(listado, CmunParametrosDTO.Orden.ByStrDescripcion .ascending());
        else Collections.sort(listado, CmunParametrosDTO.Orden.ByStrDescripcion .descending());
    

提交回复
热议问题