How to sort an array of objects containing null elements?

后端 未结 5 1831
梦谈多话
梦谈多话 2020-11-27 23:24

In my program an array fClasses of fixed length [7] of objects is created, each object is a class FClass that contains 3 Strings, an <

5条回答
  •  伪装坚强ぢ
    2020-11-27 23:50

    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, using the NullComparator as the second argument of the Collections.sort() method, as follows:

    ArrayList list = new ArrayList();
    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!

提交回复
热议问题