Sorting List of Arrays by different elements using Java 8 lambdas

java, java-8, lambda, list, sorting

Solution

Here's a couple examples. Replace x in the first two examples below with the index of the field you'd like to use for sorting.

Collections.sort(personList, (p1, p2) -> p1[x].compareTo(p2[x]));

or

personList.sort((p1, p2) -> p1[x].compareTo(p2[x]);

Also, I agree with @Robin Topper's comment. If lambdas are required (and you wanted to sort by first name), you could use:

Collections.sort(personList, (p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));

or

personList.sort((p1, p2) -> p1.getFirstName().compareTo(p2.getFirstName()));

Also consider using the comparable implementation from Robin's comment and a data-structure allowing sorting.

Problem

If I have a `List<String[]>` in which each `String[]` is as follows: {FirstName, LastName, Income, City} how would I go about using Java 8 lambdas to sort the List by a certain value such as income or first name?

Original source