按子列表的值对LIst列表进行排序

private List subList; private List<List> records = new ArrayList<List>(); for(....){ subList = new ArrayList(); ...populate.. records.add(subList); } 

例如,subList有三个字符串 – a,b和c。 我想通过subList中的b值对记录进行排序。

 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" 

排序后,记录的顺序应为 –

 records at 0 = records at 1 above records at 1 = records at 0 above records at 2 = records at 2 above 

什么可能是一个很好的算法呢?

就像是:

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

虽然我发现在实践中对位置进行硬编码有点可疑,但您的意见可能会有所不同。

这就像排序一串字符一样:给定两个字符串,从头开始并比较每个字符; 如果存在差异,则具有较低值的字符串首先出现,否则,请查看每个字符串中的下一个字符。 如果字符串具有不同的长度,则将较短的字符串视为具有零后缀。

在这种情况下,“characters”是通过调用Integer.parseInt()获得的整数值。 此外,在此处实现ListComparator会很有帮助。 然后可以使用Collections.sort()方法。

比较器可能看起来像这样:

 final class MyComparator implements Comparator> { public int compare(List a, List b) { /* Assume all strings are parseable to values * in range [0,Integer.MAX_VALUE] */ int len = Math.min(a.size(), b.size()); for (int idx = 0; idx < len; ++idx) { int va = Integer.parseInt(a.get(idx)), vb = Integer.parseInt(b.get(idx)); if (va != vb) return va - vb; } return va.size() - vb.size(); } @Override public boolean equals(Object o) { return o instanceof MyComparator; } @Override public int hashCode() { return MyComparator.class.hashCode(); } } 
 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MyList { private List> myList; public MyList() { myList = new ArrayList>(); ArrayList arrayList = null; for(int i=0;i<3;i++) { arrayList = new ArrayList(); for(int x=0;x<3;x++) { arrayList.add((Long)Math.round(Math.random()*10)); } myList.add(arrayList); } } public static void main(String[] args) { MyList newList = new MyList(); newList.printList(); Collections.sort(newList.getMyList(),new Comparator>(){ public int compare(List o1, List o2) { if(o1 != null && o2 !=null) { Long var1 = o1.get(0); Long var2 = o2.get(0); return var1.compareTo(var2); } return 0; } }); newList.printList(); } private void printList() { for(List subString : myList) { System.out.println("List"); for(Long elements : subString) { System.out.println(elements); } } } public List> getMyList() { return myList; } public void setMyList(List> myList) { this.myList = myList; } } 

Column Comparator允许您对List中的任何列进行排序。 使用列中数据的自然排序顺序完成排序。