排序 ArrayList<String>排除字符串前半部分的数字 [英] Sort ArrayList&lt;String&gt; excluding the digits on the first half of the String

查看:32
本文介绍了排序 ArrayList<String>排除字符串前半部分的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to sort an ArrayList which a series of String composed as well (XX and YY are numbers):

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

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

I would link to sort them by only considering the YY value. I found this method but it considerers all the digits of the string and I cannot remove n digits before YY because I don't know from how many digits is composed 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);
    }
});

推荐答案

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

You also need to come up with how you'd like to sort the strings that don't have a number in the second part.

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) 就足够了,你可以使用更短的比较器.

If you are sure Integer.parseInt(s.split(":")[1].trim()) never fails with an exception, Comparator.comparingInt(this::extractInt) would be enough, and you could go with a shorter comparator.

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

这篇关于排序 ArrayList<String>排除字符串前半部分的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆