Reputation: 360
Please, help me convert a HashMap<String, ArrayList<String>>
to HashMap <String, String>
, where each ArrayList
should be converted into one String
that contains the ArrayList's elments.
Upvotes: 0
Views: 891
Reputation: 14709
I believe that this is what you are looking for.
//HashMap<String, ArrayList<String>> hashMap;
//initialized somewhere above
HashMap<String, String> newHashMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
newHashMap.put(entry.getKey(), entry.getValue().toString());
}
Not sure if your issue was with toString()
or how to iterate over a HashMap, if it was the latter, here's how to iterate over a map.
Here's a from-start-to-finish example:
ArrayList<String> al = new ArrayList<>();
al.add("The");
al.add("End");
HashMap<String, ArrayList<String>> hashMap = new HashMap<>();
hashMap.put("This is", al);
HashMap<String, String> newHashMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
newHashMap.put(entry.getKey(), entry.getValue().toString());
}
System.out.println(newHashMap.toString());
//prints {This is=[The, End]}
Upvotes: 3