Search code examples
javasortingcollections

sorting a List<List<Integer>> using java Collections.sort()


I have a list of list as follow:

List<List<Integer>> matchedPostions = findTerms(originalEntPos, singularEntPos, singText);

Consider this example

[ID,StartPostion,EndPostion]
      ^^^
[1,198,200]
[2,50,61]

I am trying to sort list using Collections.sort(). How can I sort the values inside the matchedPostions based on the StartPostion values, from lower to higher values?


Solution

  • You'll need to implement a Comparator to sort custom data-structures like the one you provided.

    import static java.util.Arrays.asList;
    
    List<List<Integer>> matchedPostions = asList(asList(1, 198, 200), asList(2, 50, 61));
    Collections.sort(matchedPostions, new Comparator<List<Integer>>() {
        @Override
        public int compare(List<Integer> o1, List<Integer> o2) {
            // Sort the lists using the starting position (second element in the list)
            return o1.get(1).compareTo(o2.get(1));
        }
    });
    
    System.out.println(matchedPostions);
    // [[2, 50, 61], [1, 198, 200]]
    

    This is the "dirty" way. The more idiomatic approach is described Duncan where you implement a Range class which properly encapsulates your data.