[英]Sorting multidimensional array in java without using collections
String Name[][]={
{"prakash","kumar"},
{"raj","kappor"},
{"vinod","bhart"},
{"yraj","tkappor"},
{"avinod","fbhart"}
};
Can we sort this string array surname first, then firstname without using collections ? 我们可以不使用集合先对这个字符串数组的姓进行排序,然后对名字进行排序吗?
You can sort the arrays in place using java.util.Arrays utility class. 您可以使用java.util.Arrays实用工具类对数组进行排序。 In this case it would look something like this: 在这种情况下,它将看起来像这样:
Arrays.sort(Name, new Comparator<String[]>(){
int LASTNAME=0, FIRSTNAME=1;
@Override
public int compare(String[] o1, String[] o2) {
int c = o1[LASTNAME].compareTo(o2[LASTNAME]);
if (c != 0) return c;
return o1[FIRSTNAME].compareTo(o2[FIRSTNAME]);
}
});
You can use <T> Arrays.sort(T[] a, Comparator<? super T> c)
(see here ) to sort generic arrays and specify a custom comparator that in your case compares two String[]
by looking first at the surname and then at the first name (See Panu's answer for a possible implementation). 您可以使用<T> Arrays.sort(T[] a, Comparator<? super T> c)
(请参见此处 )对通用数组进行排序,并指定一个自定义比较器,在您的情况下,首先查看两个String[]
姓,然后名(请参阅Panu的答案以获取可能的实现)。
If you don't want to use Arrays
either, you will have to implement a sorting algorithm yourself. 如果您也不想使用Arrays
,则必须自己实现排序算法。 You can find a good overview of sorting algorithms here . 您可以在此处找到排序算法的良好概述。 In order to use your custom comparison you will have to adapt the comparison methods. 为了使用您的自定义比较,您必须调整比较方法。
Arrays.sort(Name, ComparatorFactory.compareOn(ON.FIRSTNAME));
enum ON {
FIRSTNAME, LASTNAME, FULLNAME }
class ComparatorFactroy {
static Comparator compareOn(ON on){
switch (on) {
case FIRSTNAME :
return new Comparator<String[]>() {
@Override
public int compare(String[] tar) { ... }
};
case LASTNAME :
return.....
default:
return ...
}
}
final String[][] data = new String[][] {
new String[] { "prakash","kumar" },
new String[] { "raj","kappor" },
new String[] { "vinod","bhart" },
new String[] { "yraj","tkappor" },
new String[] { "avinod","fbhart" }};
Arrays.sort(data, 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);
}
});
If you do not want to use java's inbuilt sorting mechanism then you can implement one yourself something like this: 如果您不想使用Java的内置排序机制,则可以自己实现以下内容:
for(int i=0;i<Name.length;i++) {
for(int j=i+1;j<Name.length;j++) {
if(Name[i][1].compareTo(Name[j][1])>0) {
String[] temp = Name[i];
Name[i] = Name[j];
Name[j] = temp;
}
}
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.