[java] 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.

This question is related to java android key hashmap

The answer is


you can use this code:

for (Object variableName: mapName.keySet()){
    variableKey += variableName + "\n";
    variableValue += mapName.get(variableName) + "\n";
}
System.out.println(variableKey + variableValue);

this code will make sure that all the keys are stored in a variable and then printed!


String text="";

    for (Iterator i = keys.iterator(); i.hasNext() 
       {
           String key = (String) i.next();
           String value = (String) map.get(key);
           text+=key + " = " + value;
       }

        textview.setText(text);

This code is tested and working.

public void dumpMe(Map m) { dumpMe(m, ""); }
private void dumpMe(Map m, String padding) {
  Set s = m.keySet();
  java.util.Iterator ir = s.iterator();
  while (ir.hasNext()) {
    String key = (String) ir.next();
    Object value = m.get(key);
    if (value == null) continue;
    if (value instanceof Map) {
      System.out.println (padding + key + " = {");
      dumpMe((Map)value, padding + "  ");
      System.out.println(padding + "}");          
    }
    else if (value instanceof String  ||
             value instanceof Integer ||
             value instanceof Double  ||
             value instanceof Float   ||
             value instanceof Long ) {

      System.out.println(padding + key + " = " + value.toString());
    }
    else { 
      System.out.println(padding + key + " = UNKNOWN OBJECT: " + value.toString());
      // You could also throw an exception here
    }      
  } // while

} // dumpme

Charles.


You can do it easier with Gson:

Log.i(TAG, "SomeText: " + new Gson().toJson(yourMap));

The result will look like:

I/YOURTAG: SomeText: {"key1":"value1","key2":"value2"}

Kotlin Answer

for ((key, value) in map.entries) {
    // do something with `key`
    // so something with `value`
}

You may find other solutions that include filterValues. Just keep in mind that retrieving a Key value using filterValues will include braces [].

val key = map.filterValues {it = position}.keys

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();
}

for (Map.Entry<String,String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // do stuff
}

public void dumpMe(Map m) { dumpMe(m, ""); }

private void dumpMe(Map m, String padding) 
{
    Set s = m.keySet();
    java.util.Iterator ir = s.iterator();
    while (ir.hasNext()) 
    {
        String key = (String) ir.next();
        AttributeValue value = (AttributeValue)m.get(key);
        if (value == null) 
            continue;
        if (value.getM() != null)
        {
            System.out.println (padding + key + " = {");
            dumpMe((Map)value, padding + "  ");
            System.out.println(padding + "}");          
        }
        else if (value.getS() != null  ||
                 value.getN() != null ) 
        {
            System.out.println(padding + key + " = " + value.toString());
        }
        else 
        { 
            System.out.println(padding + key + " = UNKNOWN OBJECT: " + value.toString());
            // You could also throw an exception here
        }      
    } // while
}

//This code worked for me.

With Java 8:

map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key)));

For everyone who clicked on this to find out what the content of your HashMap is, the toString method (docs) actually works with most objects. (note: a java array is not an object!)

So this woks perfectly fine for debugging purposes:

System.out.println(myMap.toString());

>>> {key1=value1, key2=value2}

    for (String entry : map.keySet()) {
      String value = map.get(entry);
      System.out.print(entry + "" + value + " ");
      // do stuff
    }

HashMap <Integer,Integer> hm = new HashMap<Integer,Integer>();

Set<Integer> keys = hm.keySet();  //get all keys
for(Integer i: keys)
{
    System.out.println(hm.get(i));
}

Java 8

map.entrySet().forEach(System.out::println);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?

Examples related to hashmap

How to split a string in two and store it in a field Printing a java map Map<String, Object> - How? Hashmap with Streams in Java 8 Streams to collect value of Map How to convert String into Hashmap in java Convert object array to hash map, indexed by an attribute value of the Object HashMap - getting First Key value The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files Sort Go map values by keys Print all key/value pairs in a Java ConcurrentHashMap creating Hashmap from a JSON String