简体   繁体   English

根据选定的列使用Arrays.sort对二维String数组进行排序

[英]Sort a two dimensional String array with Arrays.sort based on a chosen column

I have a two dimensional array filled with strings in Java. 我有一个用Java字符串填充的二维数组。 I want to be able to sort the entire array relative to the column I have chosen to sort by. 我希望能够相对于我选择作为排序依据的列对整个数组进行排序。

For Example: 例如:

Say I have an Array of data that looks like this. 假设我有一个看起来像这样的数据数组。

|John  | C | Doe    |

|Sally | A | Miller |

|Chris | B | Sanders|

I specify that I want to sort in descending order based on their middle initial and am returned an array that looks like this. 我指定我要基于中间名首字母以降序排序,并返回一个看起来像这样的数组。

|John  | C | Doe    |

|Chris | B | Sanders|

|Sally | A | Miller |

Is there a way to designate a Comparator that will do this? 有没有办法指定比较器来做到这一点?

Sure, just pass the column index in as a parameter of the comparator. 当然,只需将列索引作为比较器的参数传入即可。

class ColumnComparator<T extends Comparable<T>> implements Comparator<T[]> {
  private final int column;

  ColumnComparator(int column) { this.column = column; }

  @Override public int compare(T[] a, T[] b) {
    return a[column].compareTo(b[column]);
  }
}

or, more simply, if it is always column 1 and string arrays: 或更简单地说,如果它始终是列1和字符串数组:

class ColumnComparator implements Comparator<String[]> {
  @Override public int compare(T[] a, T[] b) {
    return a[1].compareTo(b[1]);
  }
}

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

public class Main {
    public static void main(String[] args) {
        String[][] array = {{"John", "C", "Doe"}, {"Sally", "A", "Miller"}, {"Chris", "B", "Sanders"}};
        Arrays.sort(array, new IndexComparator(0));
        for(int i = 0; i < array.length; i++) {
            System.out.println(array[i][0]);
        }
    }
}

class IndexComparator implements Comparator {
    private int index = 0;

    public IndexComparator(int index) {
        this.index = index;
    }


    @Override
    public int compare(String[] o1, String[] o2) {
        return o1[index].compareTo(o2[index]);
    }
}

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

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