67

我想ArrayList按属性排序。这是我的代码...

public class FishDB{

    public static Object Fish;
    public ArrayList<Fish> list = new ArrayList<Fish>();

    public class Fish{
        String name;
        int length;
        String LatinName;
        //etc. 

        public Vis (String name) {
            this.name = name;
        }
    }

    public FishDB() {
        Fish fish;

        fish = new Fish("Shark");
        fish.length = 200;
        fish.LatinName = "Carcharodon Carcharias";

        fish = new Fish("Rainbow Trout");
        fish.length = 80;
        fish.LatinName = "Oncorhynchus Mykiss";

        //etc.
        }
    }
}

现在我想ArrayList按一个属性对它进行排序,例如latinname在另一个活动中。但我不知道该怎么做。有人知道怎么做吗?

4

4 回答 4

157

您需要实现 a Comparator,例如:

public class FishNameComparator implements Comparator<Fish>
{
    public int compare(Fish left, Fish right) {
        return left.name.compareTo(right.name);
    }
}

然后像这样排序:

Collections.sort(fishes, new FishNameComparator());
于 2012-06-01T15:34:32.117 回答
87

您可以通过以下代码简单地做到这一点:

Collections.sort(list, new Comparator<Fish>() {
    public int compare(Fish o1, Fish o2) {
        return o1.name.compareTo(o2.name);
    }
});
于 2014-11-20T04:56:29.367 回答
2

科特林代码

list.sortWith(Comparator { o1, o2 -> o1.name!!.compareTo(o2.name!!) })
于 2020-02-06T09:26:32.737 回答
0

如何实现相同的目标有多种选择。最简单的解决方案是利用 Java 8 特性:

Collections.sort(Fish, (t1, t2) -> t1.name().compareTo(t2.name()));
于 2021-03-30T19:45:53.450 回答