73

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. What am I doing wrong?

starball
  • 20,030
  • 7
  • 43
  • 238
Gopinath
  • 5,392
  • 21
  • 64
  • 97

15 Answers15

191
for (Map.Entry<String,String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // do stuff
}
Shadow
  • 6,161
  • 3
  • 20
  • 14
13

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"}
Anh Vu
  • 219
  • 3
  • 10
12

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();
}
muffinmad
  • 641
  • 3
  • 9
11
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));
}
Abhi
  • 119
  • 1
  • 3
11

First, there are errors in your code, ie. you are missing a semicolon and a closing parenthesis in the for loop.

Then, if you are trying to append values to the view, you should use textview.appendText(), instead of .setText().

There's a similar question here: how to change text in Android TextView

Gary
  • 13,303
  • 18
  • 49
  • 71
Savino Sguera
  • 3,522
  • 21
  • 20
5

With Java 8:

map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key)));
mdev
  • 1,366
  • 17
  • 23
  • 1
    Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. – Nathan Tuggy Nov 02 '16 at 23:25
  • OP wants to print all keys and value pairs. I dont think any explanation is needed here. It is an very old thread, already answered, and also no brain thing. I have already written if someone is looking for a solution in Java8, he/she can do something like that. – mdev Nov 04 '16 at 01:37
  • 1
    mdev - There are many newbies here who would benefit from an explanation, even if it is obvious to an expert like you. If you would have provided an explanation, you might have discovered that your solution is incorrect; (teh "result" variable is unspecified). It should be: map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key))); Where the -> separates the parameters (left-side) from the implementation (right side). See https://howtodoinjava.com/java8/foreach-method-example/ and https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html – Tihamer Mar 30 '20 at 18:36
  • Tihamer Thanks for pointing the typo. I have edited the answer. – mdev Mar 31 '20 at 03:36
  • The OP wants to *display* all the keys and values in a text field, and his only problem is in that part of it. – user207421 Mar 31 '20 at 04:08
5

Java 8

map.entrySet().forEach(System.out::println);
bluehallu
  • 10,205
  • 9
  • 44
  • 61
4
    for (String entry : map.keySet()) {
      String value = map.get(entry);
      System.out.print(entry + "" + value + " ");
      // do stuff
    }
Sundresh
  • 185
  • 5
2
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);
jeet
  • 29,001
  • 6
  • 52
  • 53
1

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.

ChopperCharles
  • 747
  • 2
  • 9
  • 19
1

To print all keys:

myMap.keys().toList().joinToString()

To print all entries:

myMap.map { "${it.key} :: ${it.value}" }.toList().joinToString()
Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
0

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!

kakaday22
  • 157
  • 1
  • 8
0
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.
-1

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}
petroni
  • 766
  • 1
  • 13
  • 29
-1

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
portfoliobuilder
  • 7,556
  • 14
  • 76
  • 136