How to sort HashMap as added in Android with ArrayAdapter

I have a HashMap<String,String> , and have a static method that returns this map in Activity .

The method is as follows:

 public static HashMap<String, String> getAll() { HashMap<String, String> map = new HashMap<String,String>(); map.put("ab", "value1"); map.put("bc", "value2"); map.put("de", "value3"); return map; } 

I want to use this card with a counter. Thus, the activity is as follows:

 List list = new ArrayList<String>(); HashMap<String, String> map = Constants.getAll(); for (String key : map.keySet()) { list.add(Constants.getAll().get(key).toString()); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinTest = (Spinner)findViewById(R.id.spinTest); spinTest.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { urlDebug.setText(list.get(arg2).toString()); } public void onNothingSelected(AdapterView<?> arg0) { } }); spinTest.setAdapter(adapter); 

When I tried to run the application, no problem. But when I clicked on spinner, elements that were not ordered when I added the getAll () method. I mean, the order must be ab-bc -de, but it is ordered randomly.

What's wrong?

+6
source share
3 answers

in hashmap, the insertion order is not supported, so the last element to which the last can be added can be accessed first. If you want to keep the insertion order, use a linkedhashmap instead.

+6
source

Update: jitendra sharma's answer is better: Treemap costs a lot more than the associated hashmap and adds nothing to your project if you need to keep the original insertion order.

Hashmap cannot be sorted. This is part of their effectiveness.

If you need sorting, use TreeMap .

Good luck.

+2
source

After sorting the list, you must either call the adapter .notifyDataSetChanged () or spinTest.setAdapter (adapter).

 spinTest.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { urlDebug.setText(list.get(arg2).toString()); } public void onNothingSelected(AdapterView<?> arg0) { } }); spinTest.setAdapter(adapter); // TODO: Sort the list // Some code here adapter.notifyDataSetChanged(); 
0
source

Source: https://habr.com/ru/post/907211/


All Articles