【问题标题】:Sorting list neglecting 0 when sorting is added in code在代码中添加排序时排序列表忽略 0
【发布时间】:2018-07-10 08:15:59
【问题描述】:

我正在尝试根据下面列出的练习名称对模型类列表进行排序:

练习 6、练习 3、练习 02、练习 01

添加排序代码后,列表数据如下所示

练习 3、练习 6、练习 01、练习 02

需要的结果是

练习01,练习02,练习3,练习6

以下是用于排序列表数据的代码

Collections.sort(exerciseList, new Comparator<Exercise>() {
    @Override
    public int compare(Exercise exercise, Exercise exercise1) {
        return exercise.getExercise().compareTo(exercise1.getExercise());
    }
});

任何帮助都非常感谢。

【问题讨论】:

  • 解析你的名字字符串并加上整数部分,然后使用整数进行比较。

标签: android list sorting


【解决方案1】:

这里有一个自定义比较器来解决这个问题。

Collections.sort(keyList, new Comparator<String>()
{
    @Override
    public int compare(String s1, String s2)
    {
        s1 = s1.replaceAll("[^\\d]", "" );
        s2 = s2.replaceAll("[^\\d]", "" );
        Integer val1 = Integer.parseInt(s1);
        Integer val2 = Integer.parseInt(s2);
        return val1.compareTo(val2);
    }
});

【讨论】:

  • 感谢您的回复,但我需要将排序设为全局,因为字符串练习也可以附加其他内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 2011-08-28
  • 2023-04-08
  • 2019-03-13
相关资源
最近更新 更多