How to sort an array of objects containing null elements?

删除回忆录丶 提交于 2019-11-26 23:14:07

You need your own Comparator implementation and check for nulls and return 0

 Arrays.sort(fClasses, new Comparator<FClass>() {
    @Override
    public int compare(FClass o1, FClass o2) {
        if (o1 == null && o2 == null) {
            return 0;
        }
        if (o1 == null) {
            return 1;
        }
        if (o2 == null) {
            return -1;
        }
        return o1.compareTo(o2);
    }});

Using Java 8, you can easily build the comparator you need:

Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder()));

Use nullsLast instead if that's what you want, of course.

You have to create a Comparator<FClass>, rather than use a Comparable<FClass>.

public class FClassComparator implements Comparator<FClass> 
{
    public int compare(FClass left, FClass right) {
        // Swap -1 and 1 here if you want nulls to move to the front.
        if (left == null) return right == null ? 0 : 1;
        if (right == null) return -1;
        // you are now guaranteed that neither left nor right are null.

        // I'm assuming avg is int. There is also Double.compare if they aren't.
        return Integer.compare(left.avg, right.avg); 
    }
}

Then call sort via:

Arrays.sort(fClassArray, new FClassComparator());

With Apache Commons Collections 4 you can use ComparatorUtils to do that:

Collections.sort(arr, ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR));

By importing the org.apache.commons.collections.comparators package of the Apache 2.1.1 Release library, I'm able to sort a list, such as an ArrayList<String>, using the NullComparator as the second argument of the Collections.sort() method, as follows:

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
list.add(null);

// Sort the list
Collections.sort(list, new NullComparator(true));

System.out.println(list);
// outputs:
// [bar, baz, foo, null]

The thing I like about this approach is that the NullComparator has an overload constructor which allows you to specify whether you want null to be considered a high value or a low value, which seems pretty intuitive to me.

NullComparator(boolean nullsAreHigh)

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!