我有一个多维String数组过程[100] [2],如下所示:

B

D



B C

E

Y

D

X

G

我想在第一列字母上对其进行排序,以便最终结果看起来像这样:



B C

D

Y

G

E

D

B

X
我试过使用下面的代码,但这不能解决问题:

Arrays.sort(process, new Comparator<String[]>() {
        @Override

        public int compare(final String[] entry1, final String[] entry2) {
                final String time1 = entry1[0];
                final String time2 = entry2[0];
                return time1.compareTo(time2);

        }
});


我得到的输出是:



B C

D

Y

E

B

G

D

X

最佳答案

以下单元测试演示了有效的Comparator实现。测试也会打印出结果。

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

import junit.framework.TestCase;

public class ArrayTest extends TestCase {

    public class Sorter implements Comparator {
        public int compare(Object o1, Object o2){
            String[] arrayOne = (String[])o1;
            String[] arrayTwo = (String[])o2;
            return arrayOne[0].compareTo(arrayTwo[0]);
        }
    }

    public void testSort() {
        String[][] testData = {
                {"Y", "B"},
                {"C", "D"},
                {"A", "B"},
                {"B", "C"},
                {"F", "E"},
                {"E", "Y"},
        };

        Arrays.sort(testData, new Sorter());

        String[][] expectedOutput = {
                {"A", "B"},
                {"B", "C"},
                {"C", "D"},
                {"E", "Y"},
                {"F", "E"},
                {"Y", "B"},
        };

        for(int i = 0; i < testData.length; ++i) {
            System.out.println(testData[i][0] + " " + testData[i][1]);
            assertEquals(expectedOutput[i][0], testData[i][0]);
            assertEquals(expectedOutput[i][1], testData[i][1]);
        }
    }
}

关于java - 用Java对多维字符数组进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5889304/

10-10 19:43