-1

Down below you'll see an outtake of my code. I need to sort the getTopBids so that the highest bid comes first and after that the second highest one etc.... How do I do this? Very new to Java - this is my first assignment in school!

   public String getTopBids(){
    StringBuilder topBids = new StringBuilder();
    ArrayList<String> topBidsName = new ArrayList<>();
    ArrayList<Integer> topBidsAmount = new ArrayList<>();
    for(int i = 0; i < 3; i++) {
        String name = "";
        int amount = 0;

        for (Bid bid : this.getBidding()) {
            if(amount < bid.getAmount() && !topBidsAmount.contains(bid.getAmount())) {
                name = bid.getUser().getName();
                amount = bid.getAmount();
            }
        }
        if(amount != 0){
            topBidsName.add(name);
            topBidsAmount.add(amount);
        }
    }
    for (int i = 0; i < topBidsName.size(); i++){
        topBids.append(String.format("%s %d kr", topBidsName.get(i),
            topBidsAmount.get(i)));
        if(i != topBidsName.size()) topBids.append(", ");
    }
    return topBids.toString(); }

}
crispycat
  • 79
  • 3
  • 8
  • https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property – BackSlash Jan 17 '19 at 14:42
  • Hi Wendela! Have you heard about the `Comparable` interface? – vikingsteve Jan 17 '19 at 14:43
  • 1
    That question might give you the answer, but I recommend trying on your own first. You should read this [Open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) – dquijada Jan 17 '19 at 14:43
  • `ArrayList` (in fact every `List`) implementation has a `sort()` method. Which sorts the contents in their natural order – Lino Jan 17 '19 at 14:43
  • In java ,there has many method to sort,like `Arrays,sort()` ,`Collections.sort()` or `Stream.sort()`. – TongChen Jan 17 '19 at 14:51

1 Answers1

0

Use

Collections.sort(topBidsAmount);

See also How to use Collections.sort() in Java?

O. Schnieders
  • 593
  • 1
  • 6
  • 16