6

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));
  }
});
8
  • Create your own Comparator, and use Collections.sort(). Commented Nov 20, 2014 at 9:01
  • 1
    Please show us the code you have tried. Commented Nov 20, 2014 at 9:01
  • I am trying to make own comparator but everytime i got wrong result. Commented Nov 20, 2014 at 9:03
  • Show us your code. Describe what you think it does. Show us the intended output. Show us the actual output of your code. Commented Nov 20, 2014 at 9:04
  • 2
    Sounds like you should use a class rather than a List with elements that have special significance at specific indexes. Commented Nov 20, 2014 at 9:11

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I made a modification
Integer.parseInt is always better, than new Integer
Yes, but i wanted to keep an object to use compareTo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.