gpt4 book ai didi

java - 按数字升序对字符串列表进行排序,并保留多个小数

转载 作者:行者123 更新时间:2023-12-02 05:37:54 27 4
gpt4 key购买 nike

我正在尝试对以下列表进行排序:

2.1.0.0
2.1.1.0
2.1.11.0
2.1.12.0
2.1.13.0
2.1.14.0
2.1.15.0
2.1.2.0
2.1.3.0
2.1.4.0
2.1.5.0
2.1.6.0
2.1.7.0
2.1.8.0
2.1.9.0

实现如下列表:

2.1.0.0
2.1.1.0
2.1.2.0
2.1.3.0
2.1.4.0
2.1.5.0
2.1.6.0
2.1.7.0
2.1.8.0
2.1.9.0
2.1.11.0
2.1.12.0
2.1.13.0
2.1.14.0
2.1.15.0

我正在尝试按第二个小数之后的顺序对此进行排序。我尝试过 Arrays.sort 但没有成功。这是我的代码

import java.util.Arrays;

public class NewSort {

public static void main(String[] args) {
String[] numbers = { "2.1.0.0", "2.1.1.0", "2.1.11.0", "2.1.12.0",
"2.1.13.0", "2.1.14.0", "2.1.15.0", "2.1.2.0", "2.1.3.0",
"2.1.4.0", "2.1.5.0", "2.1.6.0", "2.1.7.0", "2.1.8.0",
"2.1.9.0" };

Arrays.sort(numbers);

for (String number : numbers) {
System.out.println(number);
}
}

}

最佳答案

I am trying to sort this by what is after the second decimal by that order.

你可以自己写Comparator :

enum MyStringComparator implements Comparator<String> {
INSTANCE;

@Override
public int compare(String s1, String s2) {
int n1 = Integer.parseInt(s1.split("\\.")[2]);
int n2 = Integer.parseInt(s2.split("\\.")[2]);
return Integer.compare(n1, n2);
}
}

现在:

String[] numbers = { "2.1.0.0", "2.1.1.0", "2.1.11.0", "2.1.12.0",
"2.1.13.0", "2.1.14.0", "2.1.15.0", "2.1.2.0", "2.1.3.0",
"2.1.4.0", "2.1.5.0", "2.1.6.0", "2.1.7.0", "2.1.8.0",
"2.1.9.0" };

Arrays.sort(numbers, MyStringComparator.INSTANCE);

for (String number : numbers) {
System.out.println(number);
}
2.1.0.02.1.1.02.1.2.02.1.3.02.1.4.02.1.5.02.1.6.02.1.7.02.1.8.02.1.9.02.1.11.02.1.12.02.1.13.02.1.14.02.1.15.0

I'll leave it to you to incorporate any error-checking mechanism that you may need.


In Java 8 it's a lot easier:

Arrays.sort(numbers,
Comparator.comparingInt(s -> Integer.parseInt(s.split("\\.")[2])));

关于java - 按数字升序对字符串列表进行排序,并保留多个小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24807573/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com