【问题标题】:Java - Sorting integers from objects in an ArrayListJava - 从 ArrayList 中的对象中排序整数
【发布时间】:2018-03-25 21:27:30
【问题描述】:

我已经用 Boat 对象填充了一个 ArrayList。这艘船有一个名字、一个ID和一个分数。我需要将分数、整数相互比较,然后从低到高排序。

我尝试了很多,也失败了很多,我不知道该怎么做。

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

我找到了 Comparator 类,但不知道如何正确使用它。

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

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

【问题讨论】:

标签: java sorting arraylist


【解决方案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());

使用steam按score升序排序:

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

使用steam按score降序排序:

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

【讨论】:

  • 非常感谢。我已经用头撞墙这么久了。现在,当我看到我尝试做的事情以及解决方案是什么时,我感到很尴尬......哈哈
猜你喜欢
  • 1970-01-01
  • 2018-08-07
  • 2016-08-22
  • 1970-01-01
  • 2017-12-12
  • 2014-10-08
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多