分拣Java字符串的二维数组 [英] sorting 2D array of String in java

查看:98
本文介绍了分拣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()方法。此方法需要一个比较的作为参数。排序方法委托给比较,以确定是否所述数组的一个元素,必须考虑更大,更小或等于另一个元件。由于外部数组的每个元素是一个数组,比较将有比较(弓弦)阵列。

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).

的阵列必须根据其第二个元素的值进行比较。这第二个元素是这其实再presents双号的字符串。所以,你必须transorm字符串成数字,否则订单将辞书(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天全站免登陆