-1

I'm attempting to sort an ArrayList of BountyObjects by their property .getAmount() which returns a double..

I've looked at a similar question on here and it's not pointing me in the right direction, could anyone explain how I would sort this:

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
}

Any help would be greatly appreciated, thank you

JNF
  • 3,696
  • 3
  • 31
  • 64
Ali
  • 3
  • 1
  • 2

2 Answers2

2

Using Collections, you can do it like this

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

Implement the Comparable<T> interface, like so:

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;
    }
}

Then do this in main:

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());

Output:

1.0 1.5 2.0

Emile Pels
  • 3,837
  • 1
  • 15
  • 23