Reputation: 17
How to sort HashMap<String,ArrrayList<String>>
?
I am fetching contact name from phone contacts like:
"String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));"
And stored it into one HashMap<String,ArrayList<String>>
. But all contacts I am getting in unsorted order.
May I know how to sort those contacts in alphabetical order so that I can display list view in sorted order?
Upvotes: 1
Views: 272
Reputation: 1813
I used following code to get Contacts in Ascending Order of String names as follows:
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
Hope this is what you need.
Upvotes: 0
Reputation: 450
Use below class and pass List of data to the it. It will give you new sorted list.
public class CompareApp implements Comparator<AppDetails> {
private List<AppDetails> apps = new ArrayList<AppDetails>();
Context context;
public CompareApp(String str,List<AppDetails> apps, Context context) {
this.apps = apps;
this.context = context;
Collections.sort(this.apps, this);
}
@Override
public int compare(AppDetails lhs, AppDetails rhs) {
// TODO Auto-generated method stub
return lhs.label.toUpperCase().compareTo(rhs.label.toUpperCase());
}
}
Upvotes: 1
Reputation: 2073
You can retrieve your data from the database already sorted. Just use
String orderBy = ContactsContract.Contacts.DISPLAY_NAME + " DESC";
in your query. After that, usually when you need to use HashMap an have also sorted data, then you use HashMap
+ ArrayList
. In HashMap you keep normal key,value pairs, in ArrayList
you keep sorted values (in case if you have already sorted data, you add it to ArrayList
while reading, you don't need to sort again).
If you need to sort ArrayList which is value in your HashMap, you can use:
Collections.sort(yourArrayList);
Upvotes: 1