0

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

enter image description here

Addi.Star
  • 441
  • 1
  • 11
  • 32
  • i tried this solution but no success http://stackoverflow.com/questions/31342658/sort-arraylisthashmapstring-string-using-value – Addi.Star Mar 30 '17 at 22:58
  • Couldn't you just use another set or map for online status? Instead of time complexity, growing heap is better solution i guess. – Abdullah Tellioglu Mar 30 '17 at 23:00
  • actually the structure used in code is according to this pattern . so i am bound to trigger some workaround to bring those maps object first whose status value is online in listview by simpleadapter – Addi.Star Mar 30 '17 at 23:06

1 Answers1

1

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, e.g.:

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, e.g.:

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;
            }
        }
    });
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81