【发布时间】:2019-12-27 12:33:04
【问题描述】:
我正在尝试对由一系列字符串组成的 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);
}
});
【问题讨论】:
-
一个想法是将每个字符串分解为一个具有
test、genere、eta和protocollo字段的对象,并将这些对象放入一个ArrayList中。排序会容易得多。 Object 的toString方法将输出您的原始字符串。
标签: java string sorting arraylist