java - 通过其中一个属性(双值)对对象的arraylist进行排序

java - 通过其中一个属性(双值)对对象的arraylist进行排序,第1张

我正在尝试按其ArrayList的{​​{1}} BountyObject.getAmount() double进行排序List<BountyObject> sortedList = new ArrayList<BountyObject>(); for (BountyObject bo : bounties) // Where bounties is the original list of unsorted objects { // Sort them into the sorted list by bo.getAmount() - highest to lowest value }

我在这里看了一个类似的问题,并没有把我指向正确的方向,任何人都可以解释我会如何排序:

1 propInfoList, PropagateAction propagateAction) at Microsoft.SqlServer.Management.Smo.SmoDependencyDiscoverer.SfcChildrenDiscovery(HashSet

非常感谢任何帮助,谢谢

最佳答案:

2 个答案:

答案 0 :(得分:2)

使用集合,你可以这样做

Collections.sort(bounties, new Comparator<BountyObject>() {
        @Override public int compare(BountyObject bo1, BountyObject bo2) {
            return (bo1.getAmount() >  bo2.getAmount() ? 1:-1); 
        }

答案 1 :(得分:1)

实现Comparable<T>界面,如下所示:

setId(int)

然后在main中执行此操作:

class BountyObject implements Comparable<BountyObject> {

    private final double amount;

    public BountyObject(double amount) {
    this.amount = amount;
    }

    public double getAmount() {
    return amount;
    }

    @Override
    public int compareTo(BountyObject o) {
    double otherAmount = o.amount;

    if (amount == otherAmount)
        return 0;
    else if (amount > otherAmount)
        return 1;
    else
        return -1;
    }
}

输出:

List<BountyObject> sortedList = new ArrayList<>(); sortedList.add(new BountyObject(2.0)); sortedList.add(new BountyObject(1.0)); sortedList.add(new BountyObject(1.5)); Collections.sort(sortedList); for (BountyObject bo : sortedList) System.out.println(bo.getAmount());

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复