Android Joda Time,从 ISOPeriodFormat 中排序字符串时遇到问题

Android Joda Time, Having trouble sorting strings from ISOPeriodFormat

我一直在到处寻找解决方案,但找不到有效的解决方案。

我有一个 "Scoreboard" 需要显示应用程序使用 Joda Time 计算的最高 "times"(两个瞬间之间的时间段)。

所有字符串都存储在一个 ArrayList 中,并通过 ArrayAdapter 和 ListView 显示。

问题:Collections.sort 即使使用 ISO 格式似乎也无法正常工作。

我正在使用以下格式节省时间:

PeriodFormatter formatter = ISOPeriodFormat.standard();

给出了这个:"PT1M15.664S" (1 分 15 秒)

我将其转换为字符串并存储到 ArrayList 中。

如何对这些字符串进行排序,使其在我的记分牌中从最长到最短的时间排序?

我试过自然排序和字母数字比较器,但没有成功。每次超过上限(分钟、小时、天)时,值都会变成这样:

"PT2.455S"
"PT1.324S"
"PT1M15.333S"

而不是我想要的:

"PT1M15.333S"
"PT2.455S"
"PT1.324S"

使用Collection.sort(myArrayList) 也不起作用。

知道我应该做什么吗?

我的代码:

 // set is a set<String> retrieving it's values from a stringset scores saved
in the sharedpreferences of the app

 set = sharedPreferences.getStringSet("scores", null);

 //scores is the ArrayList
 scores.clear();


  if (set != null){

      scores.addAll(set);

  }else{

      scores.add("No Time Yet!");
      set = new LinkedHashSet<String>();
      set.addAll(scores);
      sharedPreferences.edit().putStringSet("scores",set).apply();
  }

//removing the String No Time Yet because it no longer serves a purpose here
  if ((set != null)&& (set.size()>1)){
      scores.remove("No Time Yet!");
  }


    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,scores);

listView.setAdapter(arrayAdapter);

Collections.sort(scores);

感谢您的宝贵时间。

简答: 使用 class Duration,而不是 Period.

解释:

您使用 class Period 的一般方法是错误的。这种类型表示各种数量单位对的元组。其中一些不可兑换或不可比。例如,无法确定 P30D 是否大于或等于或小于 P1M(想想二月、四月或八月)。所以很清楚为什么 你不能按句点 排序。为什么这个 class 没有实现接口 Comparable。这个异议对于类型 Period 的对象及其规范的 ISO 表示(作为字符串)是有效的。

但是既然你想要

the highest "times" (period between two instants)

您可以使用 Duration 来确定两个给定时刻之间经过的秒数和毫秒数的绝对值。这种类型是可比较的,只有两个对你来说可能不重要的小限制:

  • 精确到毫秒
  • 忽略闰秒

我建议比较持续时间对象,而不是字符串,因为您需要按时间顺序排列,而不是按字典顺序排列。因此,您可以使用 Duration 的字符串表示形式(如 PT72.345S)进行存储,但解析它以进行比较:

Instant i1 = new Instant(0);
Instant i2 = new Instant(72_345);
Duration d1 = new Duration(i1, i2);

Instant i3 = new Instant(60_000);
Instant i4 = new Instant(200_710);
Duration d2 = new Duration(i3, i4);

List<String> scoreTimes = new ArrayList<>();
scoreTimes.add(d1.toString());
scoreTimes.add(d2.toString());

// order from longest times to shortest times
Collections.sort(
    scoreTimes,
    new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            return Duration.parse(s2).compareTo(Duration.parse(s1));
        }
    }
);

System.out.println(scoreTimes); // [PT140.710S, PT72.345S]