Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<HashMap<String,String>> in alphabetical order

Tags:

java

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.

like image 342
Luca Avatar asked Nov 28 '22 11:11

Luca


2 Answers

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.

like image 38
jiangws88 Avatar answered Dec 14 '22 21:12

jiangws88


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.

like image 120
Stephen C Avatar answered Dec 14 '22 20:12

Stephen C