开发者

Generic comparator to sort Java Collections (List, Set)

I need some generic comparator which would accept instances of List or Set as an argument, and order direction argument (ASC, DESC), and then return the sorted collection. I can not seem to find on internet this example, and am in a horrible rush. I know I dont ask question in appropriate way, since I dont have any code to begin with but am in a horrible rush. Collections will contain objects which implement comparable and dates.

Any examples, implementations very much appreciated. 开发者_开发问答Thank you.


The Collections class has a reverseOrder method which returns a comparator for a generic type T which should satisfy your requirement for the DESC comparator. If you are passing your Collection to the Collections.sort() method, it automatically uses the ASC sort.

Also, "sorting" doesn't mean a lot when it comes to "sets" which maintain "unique" elements in an unordered fashion (I mean you can use TreeSet for sorted sets, but that's a different story). A simple workaround would be to make a List out of the Set and pass it to Collections.sort.


Using GenericComparator.java you will be able to sort following datatypes Integer, String, Long, Double, Float, and Date.

For Ascending order

Collections.sort(persons, new GenericComparator("name", true));

For Descending order

Collections.sort(persons, new GenericComparator("name", false));

Detailed information here!


This might work as a basic kick-off example to start with your requirement :

// Create a list
String[] strArray = new String[] {"z", "a", "C"};
List list = Arrays.asList(strArray);

// Sort
Collections.sort(list);
// C, a, z

// Case-insensitive sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// a, C, z

// Reverse-order sort
Collections.sort(list, Collections.reverseOrder());
// z, a, C

// Case-insensitive reverse-order sort
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(list);
// z, C, a


You have to call your comparator by using following code.

Collection.sort(myList,new MyComparatorClass());

Then you have to create your own comparator class which will perform sorting on your object bean either on ascending or descending order.In that class you can compare the property on which you want to perform sort.Here I perform sorting on the name.

public class MyComparator  implements Comparator {

    public int compare(Object o1, Object o2) {
      return o1.getName().compareTo(o2.getName());
    }

}


Here's my Java 8 generic comparator. You can compare any T on a function f(T) -> R, e.g. Person (T) on birth-date (R). Since f can be a method reference to a getter of T, it's easy to compare on any property (field) of T. It caters for null T's and null R's (you decide whether nulls go first or last), as well as ascending/descending order. Since it uses the natural ordering of R, the latter must also implement Comparable. See usage example at end of code.

public class CompareUtil {

    public static enum Nulls {FIRST, LAST};
    public static enum Order {ASCENDING, DESCENDING};

    /** Return a Comparator of T on a function f(T) -> R */
    public static <T, R extends Comparable<? super R>> Comparator<T> comparatorOf(
            Function<T, R> function,
            Order order,
            Nulls nulls) {

        Comparator<R> rComparator = Comparator.naturalOrder();

        if (order == Order.DESCENDING) {
            rComparator = rComparator.reversed();
        }
        rComparator = (nulls == Nulls.FIRST)? 
                Comparator.nullsFirst(rComparator) :
                    Comparator.nullsLast(rComparator);

        Comparator<T> tComparator = 
                Comparator.comparing(
                        function, rComparator);

        tComparator = (nulls == Nulls.FIRST)? 
                Comparator.nullsFirst(tComparator) :
                    Comparator.nullsLast(tComparator);

        return tComparator;
    }

//Example: construct a comparator that compares Events on event-date
//in descending date order, putting any nulls at the end of the result set
Comparator<Event> c = comparatorOf(Event::getDate, Order.DESCENDING, Nulls.LAST);


Define a Comparator interface like

public interface Comparator<T> {
  int compare(T o1, T o2);
  boolean equals(Object obj);
}

Write classes which are identified to be compared for example for date objects

public class DateOrderComparator implements Comparator

for Rank Comparator

public class RankCodeComparator implements Comparator

and so on...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜