Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting ArrayList of Arraylist<String> in java

I have an ArrayList of ArrayList of String.

In Outer ArrayList on each index each Inner ArrayList has four items have four parameters.

  1. Contacts Id
  2. Contacts Name
  3. Contacts Adress
  4. Contacts Number

Now I want to sort the complete ArrayList of the on the basis of Contact Name Parameter.

Means I want to access the outer Arraylist and the inner ArrayList present on each index of outer Arraylist should be sorted according to contact Name.

Comparator / Comparable Interfaces not likely to help me.

Collection.sort can't help me

Sorting Arraylist of Arraylist of Bean. I have read this post but it is for ArrayList of ArrayList<Object>. How to figure out this problem?

like image 332
Nikhil Agrawal Avatar asked Apr 24 '13 06:04

Nikhil Agrawal


People also ask

How do you sort two Arraylists?

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.

How do you sort an ArrayList of strings alphabetically?

To sort the ArrayList, you need to simply call the Collections. sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order).


Video Answer


1 Answers

Assuming your Lists in your List has Strings in the order id, name, address and number (i.e. name is at index 1), you can use a Comparator, as follows:

List<List<String>> list;
Collections.sort(list, new Comparator<List<String>> () {
    @Override
    public int compare(List<String> a, List<String> b) {
        return a.get(1).compareTo(b.get(1));
    }
});

Incidentally, it matters not that you are using ArrayList: It is good programming practice to declare variables using the abstract type, i.e. List (as I have in this code).

like image 57
Bohemian Avatar answered Oct 01 '22 14:10

Bohemian