简体   繁体   中英

How do I sort this hashmap?

for(int i=0;i<videos.length();i++){                     
    HashMap<String, String> map = new HashMap<String, String>();    
    JSONObject e = videos.getJSONObject(i);

    map.put("id",  String.valueOf(i));
    map.put("title",  e.getString("title"));
    map.put("description",  e.getString("description"));
    mylist.add(map);
}       

Hi, I am trying to sort the code above alphabetically. I know tree maps, are supposed to be used for this sorta thing, but it would be a bigger hassle to to do that. I am having errors arranging the hash map, and have looked at numerous examples.

It is not a big hassle to use a TreeMap.

    for(int i=0;i<videos.length();i++){                     
        Map<String, String> map = new TreeMap<String, String>();    
        JSONObject e = videos.getJSONObject(i);

        map.put("id",  String.valueOf(i));
        map.put("title",  e.getString("title"));
        map.put("description",  e.getString("description"));
        mylist.add(map);
    }

Even if that's a lot of hassle (eg if you made the mistake of declaring mylist to be a List<HashMap> ), you've got little choice. A HashMap is inherently unsorted / unordered and you can't change that fact. If you could use a LinkedHashMap instead, you could add the entries in alphabetical order, but if you can change the map type you may as well use a TreeMap .

You cannot sort a HashMap.

"The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not."

Cited form: http://docs.oracle.com/javase/6/docs/api/java/util/Map.html

If you're trying to sort the list, you need to implement a comparator. You can do something like this:

public class VideoComparator implements Comparator<Map<String, String>> {
    private final String key;

    public VideoComparator(String key) {
        this.key = key;
    }

    public boolean equals(Object object) {
        return this == object;
    }

    public int compare(Map<String, String> map1, Map<String, String> map2) {
        return map1.get(key).compareTo(map2.get(key));
    }
}

Then you can sort your maps by title like this:

Collections.sort(mylist, new VideoComparator("title"));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM