0

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?

1
  • Have a look at the static methods in Comparator. E.g., to sort by the third element in each array, you could use the comparator List<String[]> list = ... ; list.sort(Comparator.comparing(a -> a[2])); Commented Sep 29, 2016 at 3:27

1 Answer 1

3

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]);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Huh, wasn't aware you could pass Comparators as an argument to Collections.sort(). Cool! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.