[Solved] Java – how do I iterate through this map so method my method returns a string [closed]


A loop won’t return the String you want this way, you need to create the String and, at every loop, concatenate a new one to it:

public static String m(Map<String, String> mp)
{
   Iterator<?> it = mp.entrySet().iterator();

   String str = "{"
      + " \"SomeAttribute\": "
      + "{";

   while (it.hasNext())
   {
      Map.Entry pair = (Map.Entry) it.next();
      str += "\"" + pair.getKey() + "\": \"" + pair.getValue() + "\",";
   }

   str += "}"
      + "}";

   return str;    
}

If you don’t want to use while, you can use for, too:

public static String m(Map<String, String> mp)
{
   String str = "{"
      + " \"SomeAttribute\": "
      + "{";

   for (Map.Entry<String, String> pair : mp.entrySet())
   {
      str += "\"" + pair.getKey() + "\": \"" + pair.getValue() + "\",";
   }

   str += "}"
      + "}";

   return str;
}

solved Java – how do I iterate through this map so method my method returns a string [closed]