简体   繁体   English

按浮点值对二维 Java 数组进行排序

[英]Sort 2D Java array by float value

I've done a little java coding with some JSON values i get from the internet.我用我从互联网上得到的一些 JSON 值做了一点 java 编码。 I put the values into a string array, print it and look for the best (aka highest) score and it's "parent" data set.我将这些值放入一个字符串数组中,打印出来并寻找最好的(也就是最高的)分数,它是“父”数据集。 But finally it would be nice to have them sorted by this score automaticly.但最后最好让它们按这个分数自动排序。

The array looks like:数组看起来像:

myArray[0][0] = "John"
myArray[0][1] = "20"       //(<- int to String)
myArray[0][2] = "21.356"   //(<- float to String)
myArray[1][0] = "Sarah"    //data
myArray[1][1] = "32"       //data
myArray[1][2] = "27.045"   //score to be sorted on

Also i thought about sorting the data-sets before putting them into the array, but as they come in plain text (by reading json values from a website), i have to make a connection of the values before sorting and this is the point, where i have to pick and put them by hand in the array at first.我还考虑过在将数据集放入数组之前对其进行排序,但是由于它们以纯文本形式出现(通过从网站读取 json 值),我必须在排序之前连接这些值,这就是重点,首先,我必须手动将它们挑选并放入阵列中。

Is there an efficient way to sort the array?有没有一种有效的方法来对数组进行排序?

You can create a custom comparator if you want to sort strings using the value inside them(here score) like:如果要使用字符串中的值(此处为分数)对字符串进行排序,可以创建自定义比较器,例如:

Arrays.sort(myarray, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    });

Additionally you can write another comparator to sort the 2d array using a particular column.此外,您可以编写另一个比较器来使用特定列对二维数组进行排序。

If I understand you correctly, you can make a stream from your array and then use something like that:如果我理解正确,您可以从您的阵列中制作一个 stream ,然后使用类似的东西:

...
.sorted(Comparator.comparingDouble(Double::parseDouble))
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM