身份证号按照年排序java
时间: 2023-07-06 09:29:29 浏览: 122
您好!要按照年份对身份证号进行排序,可以按照以下步骤进行:
1. 定义一个身份证号的数组,如下所示:
```
String[] idCards = {"440582199901011234", "440582199801011234", "440582199701011234", "440582199601011234"};
```
2. 定义一个Comparator比较器,用于对数组进行排序。在比较器中,可以使用substring方法获取身份证号中的年份部分,并将其转换为整型进行比较。代码如下所示:
```
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int year1 = Integer.parseInt(o1.substring(6, 10));
int year2 = Integer.parseInt(o2.substring(6, 10));
return year1 - year2;
}
};
```
3. 调用Arrays.sort方法对数组进行排序,并传入比较器作为参数。代码如下所示:
```
Arrays.sort(idCards, comparator);
```
4. 最后,遍历排序后的数组并输出结果。代码如下所示:
```
for (String idCard : idCards) {
System.out.println(idCard);
}
```
完整代码如下所示:
```
public class IdCardSorter {
public static void main(String[] args) {
String[] idCards = {"440582199901011234", "440582199801011234", "440582199701011234", "440582199601011234"};
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int year1 = Integer.parseInt(o1.substring(6, 10));
int year2 = Integer.parseInt(o2.substring(6, 10));
return year1 - year2;
}
};
Arrays.sort(idCards, comparator);
for (String idCard : idCards) {
System.out.println(idCard);
}
}
}
```
输出结果为:
```
440582199601011234
440582199701011234
440582199801011234
440582199901011234
```
阅读全文