Jul*_*iaz 6 java arrays sorting multidimensional-array
我知道之前可能会问过这个问题,但我找不到合适的答案.所以说我有这个数组:
String [][] theArray = {{"james", "30.0"},{"joyce", "35.0"},{"frank", "3.0"}, {"zach", "34.0"}}
Run Code Online (Sandbox Code Playgroud)
有没有办法通过每个子元素的第二个元素对此数组进行降序排序.所以我会得到这样的东西.
theArray = {{"joyce", "35.0"},{"zach", "34.0"},{"james", "30.0"}, {"frank", "3.0"}}
Run Code Online (Sandbox Code Playgroud)
多谢你们
使用Arrays.sort(arr, comparator)带有自定义比较:
Arrays.sort(theArray, new Comparator<String[]>(){
@Override
public int compare(final String[] first, final String[] second){
// here you should usually check that first and second
// a) are not null and b) have at least two items
// updated after comments: comparing Double, not Strings
// makes more sense, thanks Bart Kiers
return Double.valueOf(second[1]).compareTo(
Double.valueOf(first[1])
);
}
});
System.out.println(Arrays.deepToString(theArray));
Run Code Online (Sandbox Code Playgroud)
输出:
[[joyce,35.0],[zach,34.0],[james,30.0],[frank,23.0]]
谨防:
你将对传入的数组进行排序,Arrays.sort()不会返回一个新数组(事实上它返回void).如果需要排序副本,请执行以下操作:
String[][] theCopy = Arrays.copyOf(theArray, theArray.length);
Run Code Online (Sandbox Code Playgroud)
然后执行排序theCopy,而不是theArray.
您必须使用Arrays.sort()方法.此方法将Comparator作为参数.sort方法委托给比较器,以确定是否必须将数组的一个元素视为更大,更小或等于另一个元素.由于外部数组的每个元素都是一个数组,因此比较器必须比较数组(字符串).
必须根据第二个元素的值来比较数组.第二个元素是一个String,实际上代表一个双数.因此,您必须将字符串转换为数字,否则顺序将是词典(20之前为3)而不是数字.
因此,比较器可能如下所示:
public class StrinArrayComparator implements Comparator<String[]> {
@Override
public int compare(String[] array1, String[] array2) {
// get the second element of each array, andtransform it into a Double
Double d1 = Double.valueOf(array1.[1]);
Double d2 = Double.valueOf(array2.[1]);
// since you want a descending order, you need to negate the
// comparison of the double
return -d1.compareTo(d2);
// or : return d2.compareTo(d1);
}
}
Run Code Online (Sandbox Code Playgroud)