I have an arraylist of multiple arraylists like-
ArrayList<ArrayList<String>> al1=new ArrayList<ArrayList<String>>();
the arraylist contains the elements:
[[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]]
Now i want to sort the main arraylist. Main arraylist contains 5 inner arraylists.Now the sorting must be like the 7th element of every inner arraylist is compared which is integer and inner arraylists are arranged accorting to the value of their 7th element.
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));
}
});
An ArrayList can be sorted in two ways ascending and descending order. The collection class provides two methods for sorting ArrayList. sort() and reverseOrder() for ascending and descending order respectively.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types.
Indexes in Java begin at 0
. The 7th element has the index 6
. Moreover, you have to convert the String
to int in order to be properly compared.
Try this :
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With