在 Java 中按 属性 对集合对象进行排序

Sort Collection object by property in Java

如果我想通过 CSVInputHandler class 上名为 Order 的 属性 对下面的集合进行排序,我该怎么做?我尝试了最底部的那个,但没有运气。错误显示 The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Collection<CSVInputHandler>, Comparator<CSVInputHandler>).

对象

Collection<CSVInputHandler> csvInputHandlers = new ArrayList<>(csvInputHandlerMap.values());

尝试过

  Comparator<CSVInputHandler> comparator = new Comparator<CSVInputHandler>() {
                    public int compare(CSVInputHandler c1, CSVInputHandler c2) {
                        return c1.Order < c2.Order;
                    }
                };

                Collections.sort(csvInputHandlers, comparator); 

删除 .toArray() 因为该排序方法只接受列表类型而不接受数组

Collections.sort(csvInputHandlers, comparator); 

防御

public static <T> void sort(List<T> list, Comparator<? super T> c) {

为了对集合进行排序(使用 Collections.sort),您必须明确地将其转换为列表

List<CSVInputHandler> myList = new ArrayList<>(csvInputHandlers);

Collections.sort(myList, comparator);

Collections#sort 方法作用于 Collections,因此第一个方法参数必须是 Collection(即任何具体子类型,例如 ListSet ) 当您尝试将数组元素作为第一个参数时。应该是

Collections.sort(csvInputHandlers, comparator)

Collection :

The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered

来源http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html