简体   繁体   English

用于对Java集合进行排序的通用比较器(List,Set)

[英]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. 我需要一些通用比较器,它接受List或Set的实例作为参数,并且命令方向参数(ASC,DESC),然后返回已排序的集合。 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. 谢谢。

Using GenericComparator.java you will be able to sort following datatypes Integer, String, Long, Double, Float, and Date. 使用GenericComparator.java,您将能够对以下数据类型Integer,String,Long,Double,Float和Date进行排序。

For Ascending order 对于升序

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

For Descending order 对于降序

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

Detailed information here! 详细信息在这里!

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. Collections类有一个reverseOrder方法,它返回一个泛型类型T的比较器,它应该满足你对DESC比较器的要求。 If you are passing your Collection to the Collections.sort() method, it automatically uses the ASC sort. 如果要将Collection传递给Collections.sort()方法,它会自动使用ASC排序。

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). 此外,“排序”对于以无序方式维护“唯一”元素的“集合”并不意味着很多(我的意思是你可以将TreeSet用于排序集,但这是一个不同的故事)。 A simple workaround would be to make a List out of the Set and pass it to Collections.sort . 一个简单的解决方法是做一个List出来的Set ,并把它传递给Collections.sort

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. 然后你必须创建自己的比较器类,它将按升序或降序对对象bean进行排序。在该类中,你可以比较你想要执行sort的属性。我在名称上执行排序。

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. 这是我的Java 8通用比较器。 You can compare any T on a function f(T) -> R, eg Person (T) on birth-date (R). 您可以比较函数f(T) - > R上的任何T,例如出生日期(R)上的人(T)。 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. 由于f可以是对T的getter的方法引用,因此很容易在T的任何属性(字段)上进行比较。它适用于null T和null R(您决定空值是首先还是最后),以及提升/降序排列。 Since it uses the natural ordering of R, the latter must also implement Comparable. 由于它使用R的自然顺序 ,后者也必须实现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 定义Comparator接口,如

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 对于Rank Comparator

public class RankCodeComparator implements Comparator

and so on... 等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM