【问题标题】:Android How to sort String List [duplicate]Android如何对字符串列表进行排序[重复]
【发布时间】:2014-01-27 21:11:44
【问题描述】:

我有一个包含这种值的列表:

列表[0] = "myvalue_8" 列表[1] = "myvalue_9" 列表[2] = "myvalue_15" list[3] = "myvalue_12"

当我像这样对列表进行排序时:

Collections.sort(myList);

结果是:

列表[0] = "myvalue_12" 列表[1] =“我的价值_15” 列表[2] = "myvalue_8" list[3] = "myvalue_9"

代替:

列表[0] = "myvalue_8" 列表[1] = "myvalue_9" 列表[2] =“我的价值_12” list[3] = "myvalue_15"

非常感谢

【问题讨论】:

  • 有关 Alphanum 算法的信息,请参阅 this question
  • 您可以随时删除字符串的“myvalue_”部分,并使用剩余的整数对自己进行排序。

标签: android string list sorting


【解决方案1】:

使用Comparator。在那里,您可以定义要比较的内容以及如何比较,在 compare() 方法中,您可以定义应该从两个实例返回的内容。这是String Comparator 的示例。

Comparator<String> myComparator = new Comparator<String>() {
  public int compare(final String user1, final String user2) {
    // This would return the ASCII representation of the first character of each string
    return (int) user2.charAt(0) - (int) user1.charAt(0);
  };
};

那你就打Collections.sort(myList, myComparator);

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2012-07-22
    • 2014-02-13
    • 2019-07-13
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多