排序多个arraylists的arraylist

时间:2014-11-20 08:58:59

标签: java string sorting arraylist

我有一个多个arraylists的arraylist,如 -

ArrayList<ArrayList<String>> al1=new ArrayList<ArrayList<String>>();

arraylist包含元素:

[[Total for all Journals, IOP, IOPscience, , , , , 86, 16, 70, 17, 8, 14, 6, 17, 19, 5], [2D Materials, IOP, IOPscience, 10.1088/issn.2053-1583, 2053-1583, , 2053-1583, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [Acta Physica Sinica (Overseas Edition), IOP, IOPscience, 10.1088/issn.1004-423X, 1004-423X, 1004-423X, , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [Advances in Natural Sciences: Nanoscience and Nanotechnology, IOP, IOPscience, 10.1088/issn.2043-6262, 2043-6262, , 2043-6262, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [Applied Physics Express, IOP, IOPscience, , 1882-0786, 1882-0778, 1882-0786, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

现在我想对主要的arraylist进行排序。主要的arraylist包含5个内部arraylists。现在排序必须像每个内部arraylist的第7个元素进行比较,这是整数和内部arraylists按照他们的第7个元素的值排列。

Collections.sort(al1, new Comparator<ArrayList<String>>() {
  @Override public int compare(ArrayList<String> o1, ArrayList<String> o2) {
    return o1.get(7).compareTo(o2.get(7));
  }
});

1 个答案:

答案 0 :(得分:1)

Java中的索引从0开始。第7个元素的索引为6。此外,您必须将String转换为int才能进行正确比较。

试试这个:

Comparator<ArrayList<String>> cmp = new Comparator<ArrayList<String>>()
{
    public int compare(ArrayList<String> a1, ArrayList<String> a2)
    {
        // TODO check for null value
        return new Integer(a1.get(6)).compareTo(new Integer(a2.get(6));
    }
};

Collections.sort(yourList, cmp);