【发布时间】:2018-08-03 14:59:32
【问题描述】:
上下文:
我有一个要排序的楼层列表,以显示在 android 的回收站视图中:
现有楼层示例:
+ 1º
+ 2º
R/C
R/C
"" -> Empty string because there is no information about it
目标: 我需要以 desc 和 asc 的方式对地板进行排序。
代码: 这是我的代码,问题是像您在上面看到的那样有带有字母和空字符串的楼层,我不能在字母和空字符串中执行 Integer.parseInt(给出了 NumberFormatException)。我正在进行这种转换,因为我认为我需要将变量传递给 Int 以进行排序。我想我不能这样做,因为地板可能包含您在示例中看到的字母。
Collections.sort(listUAs, new Comparator<ModelUA>() {
@Override
public int compare(ModelUA lhs, ModelUA rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
int floorLhs = Integer.parseInt(lhs.getFloor().replaceAll("[^\\d]", ""));
int floorIntRhs = Integer.parseInt(rhs.getFloor().replaceAll("[^\\d]", ""));
return Integer.compare(floorIntRhs, floorLhs);
}
});
谁能有更好的解决方案或改进?
【问题讨论】:
-
为什么是 -1 @Carcigenicate 以及为什么是空编辑?你没有理由拒绝我
-
我没有投反对票。但是,我确实删除了前缀选项卡,因为这会导致您的“上下文”被格式化为代码,这妨碍了可读性。
-
@Carcigenicate 你能帮我解决这个问题吗?
-
Strings 已经提供了一个
compare方法,该方法允许字典比较 afaik。你不能直接比较字符串吗?为什么需要解析它们? -
摆脱对
Integer/parseInt的调用,然后返回floorLhs.compareTo(floorRhs)。
标签: java arrays sorting collections android-recyclerview