I have an ArrayList of ArrayList of String.
In Outer ArrayList on each index each Inner ArrayList has four items have four parameters.
- Contacts Id
- Contacts Name
- Contacts Adress
- 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?
I think this is a case of not treating collections as first-class objects. Have a new class called "Contact" instead of abstracting it as an ArrayList, and use the Comparator.
Use the following Comparator:
Here
indexToCompare
is the index of the arraylist which corresponds to Contact Name. In your case "1"I guess I just assumed you had to sort a list of string arrays... thats why I sorted the list of inner arrays first, then sorted the outer list by comparing the 1st item of each array. Didnt read the contacts you had in your answer.
In that case remove the for loop for sorting the inner list and you should still be able to sort using the comparator, but compare to the right index instead of the 1st element.
Collections.sort(listOfLists, new ListOfStringListComparator());
Incorrect. You do have objects. All of the things you are trying to sort are objects.
If you are trying to sort the
ArrayList<String>
objects in anArrayList<ArrayList<String>>
, you need to implement aComparator<ArrayList<String>>
. (The Comparable approach is the wrong one for this data structure. You would need to declare a custom subclass of ArrayList ... and that's yuck!)But a better idea would be to represent your objects with custom classes. In this case, your
ArrayList of String
should be a customContact
class with 4 fields, getters and (if required) setters. Then you declare that as implementingComparable<Contact>
, and implement thecompareTo
method.Other Answers show how to implement a Comparator based on just one field of the list. That may be sufficient, but it will give you a sort order where the order of a pair of different "John Smith"s would be indeterminate. (I would use a second field as a tie-breaker. The Id field would be ideal if the ids are unique.)
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: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).I feel bad posting this, because
List<Contact>
would be the much better choice. Something like this would be possible, though: