简体   繁体   中英

Java - Sorting integers from objects in an ArrayList

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM