我对 Comparable 的实现出了点问题

Something's wrong with my implementation of Comparable

所以我尝试使用 treeMap 来创建数据集合,然后我想在使用我自己的比较器时获得一个排序列表。

我的问题是 Collections.sort 抛出错误,因为 Can only iterate over an array or an instance of java.lang.Iterable 但是我的 extsListed 是 ArrayList 类型,它确实是 Iterable 可以在这里看到 http://docs.oracle.com/javase/8/docs/api/java/util/List.html

    List<FileInfo> extsListed = new ArrayList<FileInfo>(exts.values());

    for (FileInfo info : Collections.sort(extsListed)) {
        System.out.println(info.key + ' ' + info.count + ' ' + info.size);
    }

    System.out.println(totalFound.toString() + ' ' + totalSize);
}

public static class FileInfo implements Comparable<FileInfo>{
    String key;
    Integer count;
    Long size;

    public FileInfo(String key, File file){
        count = 1;
        this.key = key;
        this.size = file.length();
    }

    public int compareTo(FileInfo other) {
        if (this.size > other.size) return 1;
        else if (this.size == other.size) {
            if (this.key.compareTo(other.key) >= 1) return 1;
            else if (this.key.equals(other.key)) return 0;
            else return -1;
        }
        else return -1;
    }
}

Collections.sortreturns void。它不会 return 为您排序的集合。您可以在调用 sort:

后简单地遍历集合本身
Collections.sort(extsListed);
for (FileInfo info : extsListed) {
   ...

集合sort 是空的。所以它没有 return 一个值:

变化:

  List<FileInfo> extsListed = new ArrayList<FileInfo>(exts.values());

    for (FileInfo info : Collections.sort(extsListed)) {
        System.out.println(info.key + ' ' + info.count + ' ' + info.size);
    }

收件人:

   List<FileInfo> extsListed = new ArrayList<FileInfo>(exts.values());
   Collections.sort(extsListed);
    for (FileInfo info : extsListed) {
        System.out.println(info.key + ' ' + info.count + ' ' + info.size);
    }

在Java8中可以写

public static class FileInfo implements Comparable<FileInfo>{
    String key;
    int count; // don't use a wrapper unless you want it to be null.
    long size;

    public FileInfo(String key, File file){
        count = 1;
        this.key = key;
        this.size = file.length();
    }

    public int compareTo(FileInfo other) {
        int cmp = Integer.compare(size, other.size);
        if (cmp == 0)
            cmp = key.compareTo(other.key);
        return cmp;
    }
}

然后你可以用

对集合进行排序
extsListed.sort();

另一种方法是完全不使用 Comparable。

public static class FileInfo implements Comparable<FileInfo>{
    final String key;
    final int count; // don't use a wrapper unless you want it to be null.
    final long size;

    public FileInfo(String key, File file){
        count = 1;
        this.key = key;
        this.size = file.length();
    }
    public String getKey() { return key; }
    public long getSize() { return size; }
    public String toString() { return key + ' ' + size + ' ' + count; }
}


exts.values().stream()
              .sort(comparing(FileInfo::getSize).andThen(FileInfo::getKey))
              .forEach(System.out::println);

一些可能有用的链接