How can I order an ArrayList of HashMaps by the key of the Hashmap? I've a list of names and numbers (saved as string) inside an ArrayList.
I think the asker wants to know how to sort ArrayList of HashMap(String,String) because Android needs this structure for adding menuItems to ListView.
You can use:
//Sort the filenames by songTitle
Collections.sort(Arraylist,new Comparator<HashMap<String,String>>(){
public int compare(HashMap<String,String> mapping1,HashMap<String,String> mapping2){
return mapping1.get("Name").compareTo(mapping2.get("Name"));
}
In most case, HashMaps have same key , so you can use my code.( You can change the "Name" to your key.
I've a list of names and numbers(saved as string) inside an arralist.
I think the real problem here (i.e. why you are having difficulty describing and implementing this) is that you are using the wrong data structure. If the objects in the ArrayList are intended to be lists, then you should not represent them using HashMaps. HashMaps are not lists of pairs since they do not preserve the order of the pairs. And by the sounds of it, you need that order to be preserved to give you the criterion for ordering the "list of pair" data structures in the larger ArrayList.
If my understanding is correct, then you will have difficulty ordering the ArrayList ... until you fix the problem of how the inner "lists" are represented. It is not clear what that fix should be:
Maybe it needs to be ArrayList<Pair<String,String>>
where Pair
is a simple tuple. This will allow you to order the lists based on the insertion order of their elements.
Maybe it needs to be LinkedHashMap<String,String>
. This also allows you to order the lists based on the insertion order of their elements, while still supporting fast lookup by name ... if that is important.
Maybe it needs to be TreeMap<String, String>
. This allows you to order on the keys (names in your case).
Maybe it needs to be TreeSet<Pair<String, String>>
. This allows you to order on the either the keys (names) or the values, or some combination thereof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With