Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all key and values from HashMap in Android?

I am very new for Android development, and I am trying to use HashMap in Android sample project. Now, am doing sample project for learn android. I just store keys and values in HashMap, i want to show the keys and their values in EditView. I followed below code in my sample project. But, first key and value only printing in EditView.

   Map<String, String> map = new HashMap<String,String>();    map.put("iOS", "100");    map.put("Android", "101");    map.put("Java", "102");    map.put(".Net", "103");     Set keys = map.keySet();     for (Iterator i = keys.iterator(); i.hasNext(); ) {        String key = (String) i.next();        String value = (String) map.get(key);        textview.setText(key + " = " + value);    } 

In EditView iOS = 100 is only printing. I want to print all keys and their value in EditText. Can anyone please tell me where i am doing wrong? Thanks in advance.

like image 426
Gopinath Avatar asked Jan 18 '12 12:01

Gopinath


People also ask

How print out keys and values in HashMap?

Print HashMap Elements in Java This is the simplest way to print HashMap in Java. Just pass the reference of HashMap into the println() method, and it will print key-value pairs into the curly braces.

How do I print a HashMap element?

This is the most basic and easiest method to print out HashMap in java. Pass the HashMap reference to the System. out. println, and the HashMap will output the key-value of the elements enclosed in curly brackets.

How to print value from map in java?

Using toString() For displaying all keys or values present on the map, we can simply print the string representation of keySet() and values() , respectively. That's all about printing out all keys and values from a Map in Java.


2 Answers

for (Map.Entry<String,String> entry : map.entrySet()) {   String key = entry.getKey();   String value = entry.getValue();   // do stuff } 
like image 190
Shadow Avatar answered Sep 25 '22 16:09

Shadow


It's because your TextView recieve new text on every iteration and previuos value thrown away. Concatenate strings by StringBuilder and set TextView value after loop. Also you can use this type of loop:

for (Map.Entry<String, String> e : map.entrySet()) {     //to get key     e.getKey();     //and to get value     e.getValue(); } 
like image 36
muffinmad Avatar answered Sep 24 '22 16:09

muffinmad