i am adding data to ArrayList < HashMap < String, Object>> contactList;
i want to sort the contactList as per their single field .
i am adding data like this :
HashMap<String, Object> docs = new HashMap<>();
docs.put("name", key);
docs.put("speciality", speci);
docs.put("status", status); // sort by this field , if contains online it should appear first .
docs.put("picture", bp);
docs.put("education", educate);
docs.put("experience", experi);
docs.put("rating", ft);
contactList.add(docs);
data is added in a loop and later i assign contactList to simpleAdapter for listview.
Now i want my contact list to compare the 'status' field , if status is 'online' show first or if all status are offline do nothing just show all ;
how can i sort my data , i need to use this data later in listView to show online status contacts first in listview. Any help Would be appreciated. Thanks
You can define a comparator by anonymous inner class
and sort based on value of status
field assuming it's always going to be a String
, eg:
contactList.sort(new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
if(null != o1.get("status") && null != o1.get("status")){
return o2.get("status").toString().compareTo(o1.get("status").toString());
}else if(null != o1.get("status")){
return 1;
}else{
return -1;
}
}
});
Update
You can use Collections.sort
if list.sort
is not compatible with current API version, eg:
Collections.sort(contactList, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
if(null != o1.get("status") && null != o1.get("status")){
return o2.get("status").toString().compareTo(o1.get("status").toString());
}else if(null != o1.get("status")){
return 1;
}else{
return -1;
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.