java - 排序数组列表不包括字符串前半部分的数字
问题描述
我正在尝试对由一系列字符串组成的 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())));
推荐阅读
- macos - 为什么沙盒不会阻止我的应用程序访问任意 URL?
- redux - TypeError:componentDidMount 内的 defaultPieces 不是函数
- import - 使用 Hcatalog 导入 sqoop 时遇到权限问题
- c# - 守护程序服务器可以使用 Azure App Service 提供的内置身份验证吗?
- c++ - OpenCV 错误:相机校准:matrix_wrap.cpp 中的断言失败
- assembly - 等效于 LLVM 的 --keep-locals
- php - 使用 PHP 在 localhost 上发送电子邮件
- java - MPAndroidChart 不断抛出空错误
- javascript - 带有redux的RxJS - 完成时发出动作(使用mergeMap)
- pentaho - Pentaho 报表设计器 - 导出报表时交替出现空白行