Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
user261002 Avatar asked Apr 01 '26 05:04

user261002


1 Answers

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.

like image 191
Matt Avatar answered Apr 02 '26 19:04

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!