java - 我应该如何按 ArrayList 中包含的一些整数对它进行排序?

标签 java sorting arraylist

这显然不是我的作品,只是一个例子。 我已经使用 Comparable、compareTo、compare、Collections、sort 等工作了两个多小时。 这不涉及对附加的字符串进行排序,但第一个数字应该与它们各自的单词保持一致。 ArrayList 必须保持完整,但我已经用尽了据我所知的所有其他可能性。

    6 Worda
    8 Wordb
    7 Wordc
    20 Wordd
    2 Worde
    5 Wordf
    1 Wordg
    10 Wordh
    1 Wordi
    2 Wordj

新的 ArrayList 类似于:

    1 Wordi
    1 Wordg
    2 Wordj
    2 Worde
    5 Wordf
    6 Worda
    8 Wordb
    7 Wordc
    10 Wordh
    20 Wordd

最佳答案

  1. 创建一个类,其中包含字段来保存每行的信息(这里是一个 int 和一个 String),
  2. 使类与其自身具有可比性。例如,如果该类名为 MyClass,则让它实现 Comparable<MyClass>
  3. 给它一个像样的compareTo(...)方法
  4. 在此方法中,您应首先按数字字段排序,如果数字不相等则返回一个值。
  5. 然后是第二个字符串(如果两个数字相等)。
<小时/>

你说,

This is obviously not my work, but an example of it...

如果您需要更具体的帮助,请考虑发布您的实际代码及其应该保存的实际数据。

<小时/>

编辑您发布的内容:

public int compareTo(Team o) { 
   if (this.apps >= o.apps) { 
     return this.apps; 
   } else { 
     return o.apps; 
   } 
} 

如果可以的话请解释一下。

<小时/>

例如

// assuming Team has an int field, score and a String field, name
public int compareTo(Team o) { 
  if (Integer.compare(score, o.score) != 0) {
    // the scores are not the same, so return the comparison
    return Integer.compare(score, o.score)
  } else {
    // the scores are the same, so compare the Strings:
    return name.compareTo(o.name);
  } 
} 

关于java - 我应该如何按 ArrayList 中包含的一些整数对它进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427843/

相关文章:

java - 无法使用 Java PreparedStatement 在 MySQL 中存储 UTF-8 内容

通过将字符串转换为日期格式来对 Javascript 日期进行排序

c++ - std::sort() 不适用于成对 vector

java - java.util.Collections.shuffle(List list) 可以按照与 "sent to be shuffled"相同的顺序返回列表吗?

java - 提高列表和 map 的合成速度

java - 将列表添加到另一个列表

java - 带方法的二叉树数据结构

java - TemporalAdjuster - 从调整后的日期获取下一个日期

java - Flink 1.9.1 无法再连接到 Azure Event Hub

c# - 通用列表的动态排序标准