java - 对 ArrayList<String> 进行排序,排除字符串前半部分的数字

标签 java string sorting arraylist

我正在尝试对由一系列字符串组成的 ArrayList 进行排序(XX 和 YY 是数字):

Test: XX    Genere: Maschio    Eta: YY    Protocollo: A

我会链接以仅考虑 YY 值对它们进行排序。我找到了这个方法,但它考虑了字符串的所有数字,我无法删除 YY 之前的 n 数字,因为我不知道 XX 由多少数字组成:

Collections.sort(strings, new Comparator<String>() {
    public int compare(String o1, String o2) {
        return extractInt(o1) - extractInt(o2);
    }

    int extractInt(String s) {
        String num = s.replaceAll("\\D", "");
        // return 0 if no digits found
        return num.isEmpty() ? 0 : Integer.parseInt(num);
    }
});

最佳答案

您还需要想出您希望如何对第二部分中没有数字的字符串进行排序。

Collections.sort(strings, new Comparator<String>() {
  public int compare(String o1, String o2) {
    return Comparator.comparingInt(this::extractInt)
        .thenComparing(Comparator.naturalOrder())
        .compare(o1, o2);
  }

  private int extractInt(String s) {
    try {
      return Integer.parseInt(s.split(":")[1].trim());
    }
    catch (NumberFormatException exception) {
      // if the given String has no number in the second part,
      // I treat such Strings equally, and compare them naturally later
      return -1;
    }
  }
});

更新

如果您确定 Integer.parseInt(s.split(":")[1].trim()) 永远不会因异常而失败,Comparator.comparingInt(this::extractInt) 就足够了,您可以使用更短的比较器。

Collections.sort(strings, 
  Comparator.comparingInt(s -> Integer.parseInt(s.split(":")[1].trim())));

关于java - 对 ArrayList<String> 进行排序,排除字符串前半部分的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57605015/

相关文章:

java - 如何在非 java 项目上运行 junit 测试

java - 为什么Hibernate会主动持久化一个对象?

Java resultSet getInt() 无返回值

python - 如何从字符串python中删除所有表情符号(unicode)字符

c++ - 在用 C++ 编写字符串的过程中按 'Enter'

javascript - 是否必须使用比较函数对数字数组进行排序?

java - 当运行不应该运行的代码时,我应该抛出什么异常?

c# - 在 C# 中将字符串中的多个字符替换为多个值

c# - 如何对一堆 N x M 二进制矩阵进行排序,以便最相似的是双向链表中的邻居?

c++ - 使用 Boost lambda 和绑定(bind)排序时出错