0

I have populated an ArrayList with Boat objects. The boat has a name, an ID and a score. I need to compare the scores, integers, with eachother and order them from lowest to highest.

I've tried a lot, and failed a lot and I'm stumped on what to do.

public class Boat {
private String name;
private int id;
private int score;

//Constructor
public Boat(String name, int id, int score) {
    this.name = name;
    this.id = id;
    this.score = score;
}

I've found the Comparator class, but can't figure out how to use it properly.

Basically what I need to do is to sort the scores into a new ArrayList. Moving them from my private ArrayList<Boat> participants; list to my private ArrayList<Boat> sortedScoreList; list in descending order.

This is my first time posting on here, so please let me know if I need to add more information.

  • 1
    Possible duplicate of [How to use Comparator in Java to sort](https://stackoverflow.com/questions/2839137/how-to-use-comparator-in-java-to-sort) – Titus Mar 25 '18 at 21:30
  • 1
    I think your question contradicts itself. Do you want descending, or lowest to highest? – cpp beginner Mar 25 '18 at 21:31
  • Possible duplicate of [How to properly compare two Integers in Java?](https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java) – hovanessyan Mar 25 '18 at 21:51
  • I meant from lowest to highest score, so ascending... Too tired to think I guess. – Benjamin A G Sandøy Mar 25 '18 at 22:06

1 Answers1

1

Using the default sort method to sort by score ascending:

ArrayList<Boat> sortedScoreList = new ArrayList<>(participants);
sortedScoreList.sort(Comparator.comparingInt(Boat::getScore));

Using the default sort method to sort by score descending:

ArrayList<Boat> sortedScoreList = new ArrayList<>(participants);
sortedScoreList.sort(Comparator.comparingInt(Boat::getScore).reversed());

Using steams to sort by score ascending:

ArrayList<Boat> sortedScoreList = 
            participants.stream()
                        .sorted(Comparator.comparingInt(Boat::getScore))
                        .collect(toCollection(ArrayList::new));

Using steams to sort by score descending:

ArrayList<Boat> sortedScoreList =
            participants.stream()
                        .sorted(Comparator.comparingInt(Boat::getScore).reversed())
                        .collect(toCollection(ArrayList::new));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Thanks so much. I've been banging my head against the wall for so long. Now I'm just embarrassed when I look at what I tried to do and what the solution was... hah – Benjamin A G Sandøy Mar 25 '18 at 22:09