简体   繁体   English

如何基于一列对一维(或二维)数组(多维)排序?

[英]How can I sort a one (or two) dimensional array (multidimensional) based on one column?

I have an array of comma separated strings in an android project as follows: 我在android项目中有一个用逗号分隔的字符串数组,如下所示:

1,orange,$5
2,apple,$6
3,banana,$8

I want to sort the array by a field, say by the 2nd field as apple, banana, orange... 我想按一个字段对数组进行排序,例如第二个字段,如苹果,香蕉,橘子...

What would be the best data structure or algorithm to handle this? 什么是处理此问题的最佳数据结构或算法?

Sort your array with a custom comparator: 使用自定义比较器对数组进行排序:

import java.util.Arrays;
import java.util.Comparator;

class Fruits {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "1", "orange", "$5" },
                new String[] { "2", "apple", "$6" },
                new String[] { "3", "banana", "$8" } };

        Arrays.sort(data, new Comparator<String[]>() {
            @Override
            public int compare(final String[] entry1, final String[] entry2) {
                final String fruit1 = entry1[1];
                final String fruit2 = entry2[1];
                return fruit1.compareTo(fruit2);
            }
        });

        for (final String[] s : data) {
            System.out.println(s[0] + " - " + s[1] + " - " + s[2]);
        }
    }

}

Output: 输出:

2 - apple - $6
3 - banana - $8
1 - orange - $5

You can read more in: 您可以阅读以下内容:

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

How does this comparator work? 该比较器如何工作?

You should model the String values into a java bean like let's say Fruit. 您应该将String值建模到Java Bean中,例如Fruit。 In that class you need to implement the Comparable interface in which you state the manner of how objects are compared. 在该类中,您需要实现Comparable接口,在其中声明比较对象的方式。 Create your objects using the newly create class and populate your objects into a list and after that, simply call Collections.sort() and you'll have your list sorted; 使用新创建的类创建对象,然后将对象填充到列表中,然后,只需调用Collections.sort()即可对列表进行排序;

Why don't you use ArrayList collection for your data, it is easy to sort data. 为什么不对数据使用ArrayList集合,对数据进行排序很容易。 You just need to implement Compralable interface in your model class and inside compareTo method write the logic of sort. 您只需要在模型类中实现Compralable接口,并在compareTo方法内部编写排序逻辑即可。 Use collection.sort() to sort the data. 使用collection.sort()对数据进行排序。

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

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