在Java中对多维字符数组进行排序
我有一个多维字符串数组过程[100][2],如下所示:
YB
CD
AB
BC
FE
EY
FD
YX
EG
我想在第一列字母上对其进行排序,以便最终结果如下:
AB
BC
CD
EY
EG
FE
FD
YB
YX 我尝试使用下面的代码,但这并不能解决问题:
Arrays.sort(process, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
我得到的输出是:
AB
BC
CD
EY
FE
YB
EG
FD
YX
I have a multi dimensional String array process[100][2] like following :
Y B
C D
A B
B C
F E
E Y
F D
Y X
E G
I want to sort it on the first column letter so that the final result will look so :
A B
B C
C D
E Y
E G
F E
F D
Y B
Y X
I've tried using the below code but that does not do the trick :
Arrays.sort(process, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
The output I get is :
A B
B C
C D
E Y
F E
Y B
E G
F D
Y X
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下单元测试演示了一个有效的
Comparator
实现。测试也会打印出结果。The following unit test demonstrates a working
Comparator
implementation. The test prints out the result as well.此代码(相同的比较器)按预期工作:
您的问题一定在其他地方。
This code (identical comparator) works as expected:
Your problem must be somewhere else.
您可能最好将每行的两个字符放在同一元素中。然后,当您需要单独的字符时,请使用
,您可以根据需要对一维数组进行排序。
You would probably be best off putting both of the characters in the same element for each row. Then, when you needed the separate characters, use
and you can sort your one-dimensional array however you like.