Java - 从ArrayList

时间:2018-03-25 21:27:31

标签: java sorting arraylist

我用Boat对象填充了一个ArrayList。船上有名字,身份证和分数。我需要将得分,整数与彼此进行比较,并从最低到最高对它们进行排序。

我已经尝试了很多次,但失败了很多,我很难知道该怎么做。

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

我找到了比较器课程,但无法弄清楚如何正确使用它。

基本上我需要做的是将分数排序到新的ArrayList中。将它们从我的private ArrayList<Boat> participants;列表中按降序移动到我的private ArrayList<Boat> sortedScoreList;列表。

这是我第一次在这里发帖,所以如果我需要添加更多信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

使用默认的sort方法按score升序排序:

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

使用默认的sort方法按score降序排序:

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

使用蒸汽按score升序排序:

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

使用steams按score降序排序:

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