在 Java 中对字符串的二维数组进行排序 [英] Sorting 2D array of strings in Java

查看:65
本文介绍了在 Java 中对字符串的二维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前可能有人问过这个问题,但我找不到合适的答案.所以说我有这个数组:

I know that this question might have been asked before, but I was not able to find a fit answer. So say I have this array:

String[][] theArray = {
        {"james", "30.0"},
        {"joyce", "35.0"},
        {"frank", "3.0"},
        {"zach", "34.0"}};

有没有办法按每个子元素的第二个元素对这个数组进行降序排序.所以我会得到这样的东西.

Is there a way to descendingly sort this array by the second element of each sub-element. So I would get something like this.

theArray = {
        {"joyce", "35.0"},
        {"zach", "34.0"},
        {"james", "30.0"},
        {"frank", "3.0"}};

推荐答案

您必须使用 Arrays.sort() 方法.此方法将 Comparator 作为参数.sort 方法委托比较器来确定数组的一个元素是否必须被视为大于、小于或等于另一个元素.由于外部数组的每个元素都是一个数组,因此比较器必须比较(字符串的)数组.

You must use the Arrays.sort() method. This method takes a Comparator as argument. The sort method delegates to the comparator to determine if one element of the array must be considered bigger, smaller or equal to another element. Since every element of the outer array is an array, the comparator will have to compare arrays (of Strings).

必须根据数组的第二个元素的值来比较数组.第二个元素是一个字符串,它实际上表示一个双数.因此,您必须将字符串转换为数字,否则顺序将是字典顺序(20 在 3 之前)而不是数字.

The arrays must be compared based on the value of their second element. This second element is a String which in fact represents a double number. So you'll have to transorm the strings into numbers, else the order will be lexicographical (20 come before 3) rather than numerical.

因此比较器可能如下所示:

The comparator could thus look like this :

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);
    }
}

这篇关于在 Java 中对字符串的二维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆