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.

4
  • 1
    Possible duplicate of How to use Comparator in Java to sort Commented Mar 25, 2018 at 21:30
  • 1
    I think your question contradicts itself. Do you want descending, or lowest to highest? Commented Mar 25, 2018 at 21:31
  • Possible duplicate of How to properly compare two Integers in Java? Commented Mar 25, 2018 at 21:51
  • I meant from lowest to highest score, so ascending... Too tired to think I guess. Commented Mar 25, 2018 at 22:06

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.