Sorting a List of LIst by the Value of the sublist

collections, java, list, sorting

Solution

Something like:

Collections.sort(records, new Comparator<List<String>>()
{
  public int compare(List<String> o1, List<String> o2)
  {
    //Simple string comparison here, add more sophisticated logic if needed.
    return o1.get(1).compareTo(o2.get(1));
  }
})

Though I find hard-coding the positions a little dubious in practice, your opinion may differ.

Problem

``` private List<String> subList; private List<List<String>> records = new ArrayList<List<String>>(); for(....){ subList = new ArrayList<String>(); ...populate.. records.add(subList); } ``` For example, subList has three Strings - a, b, and c. I want to sort the records by the value of b in subList. ``` records at 0 has a list of "10", "20", "30" records at 1 has a list of "10", "05", "30" records at 2 has a list of "10", "35", "30" ``` After the sort, the order of records should be - ``` records at 0 = records at 1 above records at 1 = records at 0 above records at 2 = records at 2 above ``` What could be a good algorithm for that?

Original source