我有一个列表如下:
List<List<Integer>> matchedPostions = findTerms(originalEntPos, singularEntPos, singText);
考虑这个例子
[ID,StartPostion,EndPostion]
^^^
[1,198,200]
[2,50,61]
我正在尝试使用 Collections.sort()
对列表进行排序。如何根据 StartPostion
值对 matchedPostions
中的值进行排序,从低到高?
最佳答案
您需要实现一个Comparator
来对您提供的自定义数据结构进行排序。
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]]
这是“肮脏”的方式。 Duncan 描述了更惯用的方法,您在其中实现了一个正确封装数据的 Range
类。
关于java - 使用 java Collections.sort() 对 List<List<Integer>> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23608964/