简体   繁体   English

Java中的Sort String []数组列表

[英]Sort String[] array list in java

I have a ArrayList<String[]> . 我有一个ArrayList<String[]>

example element: 示例元素:

test,400000,30

So the Array list contains this type of String arrays. 因此,数组列表包含这种类型的字符串数组。 Lets divide last value by middle value in one array. 让我们在一个数组中将最后一个值除以中间值。 so it will be like this. 所以会是这样。

30/400000 = 0.000075

I need to sort the array list by these values (lastvalue/middlevalue) in ascending order. 我需要按照这些值(lastvalue / middlevalue)的升序对数组列表进行排序。

How can I do that? 我怎样才能做到这一点?

You can write your custom Comparator : 您可以编写自定义Comparator

public class StringArrayComparator implements Comparator<String[]> {
    @Override
    public int compare(String[] a, String[] b) {
        double aVal = Double.valueOf (a[2]) / Double.valueOf (a[1]);
        double bVal = Double.valueOf (b[2]) / Double.valueOf (b[1]);

        return Double.compare(aVal, bVal);
    }
}

And then use it with Collections.sort : 然后将其与Collections.sort一起使用:

List<String[]> myList = /* some value */;
Collections.sort(myList, new StringArrayComparator());

Note: 注意:
This implementation assumes valid input - that all the arrays are (at least) three elements long, that the second and third elements are parsable to integers, and that the second element (which we divide by) isn't zero. 此实现假定输入有效-所有数组(至少)长三个元素,第二个和第三个元素可解析为整数,并且第二个元素(我们除以)不为零。

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

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