KaliMa
KaliMa

Reputation: 2060

Sort a List of String[]s?

In Java I have List<String[]> myList and I would like to be able to sort it in various ways. For example sort it by row[0], or maybe row[0] and then by row[1], etc, where row[i] is the String[] at index i.

Can this be done or does Java not support it?

Upvotes: 0

Views: 69

Answers (1)

passion
passion

Reputation: 1360

An example of JDK1.7. You can change index in the comparator implementation .

List<String[]> myList = new ArrayList<String[]>();

myList.add(new String[]{"a","g","x"});
myList.add(new String[]{"c","f","y"});
myList.add(new String[]{"b","d","z"});

Collections.sort(myList, new Comparator<String[]>() {
    @Override
    public int compare(String[] o1, String[] o2) {
    return o1[0].compareTo(o2[0]);
    }
});

Upvotes: 3

Related Questions