【问题标题】:How to sort string according to certain substrings?如何根据某些子字符串对字符串进行排序?
【发布时间】:2016-02-11 22:49:42
【问题描述】:

我有一个ArrayList<String>。列表中的条目可以是以下形式:

42356_11_1_9345668
562834_12_1_8674852_8
52423_4_2_586284_2
5234_13_9_535567

如您所见,中间部分包含日期:xx_y 是日期和月份。左边和右边的其他值可以是任意长度。有些字符串有最后一位。

我想先按照月份(xx_y 中的y)然后按照天(xx_y 中的xx)对列表进行排序。当然,月份和日期可能相等。在这种情况下,还应根据月份后的数字对其进行排序(例如第二个示例中的 8674852)。

如何做到这一点?如果使用其他数据结构更容易,那没关系,我很灵活。

【问题讨论】:

  • 使用 Collection Class 查看 Java 排序。创建一个表示此数据结构而不是字符串的新类可能是值得的。这样比较可能会更快。

标签: java string sorting


【解决方案1】:

如果您可以将它们放入其他数据结构中,那么您绝对应该这样做。每次你想用它做某事时解析一个字符串是很痛苦的。

public class Entry implements Comparable<Entry>    // Pick a more descriptive name
{
    int firstNumber;
    int month;
    int day;
    int lastNumber;

    public int compareTo(Entry other)
    {
        int comparison = month - other.month;
        if (comparison == 0)
            comparison = day - other.day;
        return comparison;
    }
}

列出这些条目,然后使用 Collections 方法对其进行排序:

Collections.sort(list);

【讨论】:

  • 不要将int 用于firstnumberlastnumber,除非您知道该数字始终是介于0 和Integer.MAX_VALUE 之间的数字。在这里使用int 完全等同于“现在是 1966 年,年份只使用两位数,因为我们还没有想到 Y2K”
  • 这只是一个简单的例子,展示了如何创建自定义数据类型,并在多个字段上排序。
  • 非常感谢您提供的示例。这非常适合排序,但是当我想直接访问具有特定月份和日期的条目时怎么办?我是否必须遍历整个排序列表?
  • 您可以在排序列表中使用Collections.binarySearch
【解决方案2】:

给定以下 Entry 类:

public class Entry{
   public String getItem(){...}
   public MonthDay getMonthDay(){...}
   public int getNumber(){...}

   public static Entry parseItem(String item){...}
}

您可以使用以下(未经测试!):

List<String> sortedItems = items.stream()
    .map(Entry::parseItem)
    .sort(Comparator.comparing(Entry::getMonthDay)
              .thenComparingInt(Entry::getNumber))
    .map(Entry::getItem)
    .collect(Collectors.toList);

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2015-08-13
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多