Sort arraylist from multiple arraylists

I have an arraylist from several arraylists like -

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

arraylist contains 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. The main arrailist contains 5 internal arraylists. Now sorting should be like the 7th element of each internal arraylist is compared, which is integer, and the internal arraylists are located according 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)); } }); 
+6
source share
1 answer

Indexes in Java start at 0 . The 7th element has an index of 6 . In addition, you need to convert String to int for proper comparison.

Try the following:

 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); 
+1
source

Source: https://habr.com/ru/post/978445/


All Articles