Reputation: 7502
I have a HashMap
with String
as key and List
as value.
Name of the HashMap
is pageMap
.
Say this pageMap
has the following key and value:
key = order
value = [page1, page2, page3]
now I want to display in the following pattern:
order
page1
page2
page3
key2
value1
value2
value3
value4
Please tell me how do I do that?
Upvotes: 1
Views: 3224
Reputation: 21914
public String formatDictionary(Map<String, List<String>> map){
String output = '';
for (String key : map.keySet()){
output = output + key + "\n";
for (String value: map.get(s)){
output = output + "\t" + value + "\n";
return output
Which is pretty similar to Jeppi's answer, but using string concatenation which is one of my favorite things about Java. I haven't run any benchmarks, but my guess is that his would be a little faster, but mine would have less overhead.
Upvotes: 0
Reputation: 7485
import java.util.*;
import java.lang.*;
public class StringListMapExample {
public static String asTreeFormattedString(HashMap<String,List<String>> map) {
final StringBuilder builder = new StringBuilder();
for (String key : map.keySet()) {
builder.append(key + "\n");
for (String string : map.get(key)) {
builder.append("\t" + string + "\n");
}
}
return builder.toString();
}
public static void main(String[] args) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put("order", Arrays.asList(new String[]{"page1", "page2", "page3"}));
System.out.println(asTreeFormattedString(map));
}
}
Upvotes: 3
Reputation: 817
Iterate using iterator through all keys of hashmap using keyset()
{
print key
Iterate through value list using iterator
{
print each value
}
}
Upvotes: 0
Reputation: 77454
Actually the solution is quite straightforward.
hashmap.get(key).iterator();
is an iterator for the list of the given key.
Why did you not try to figure it out yourself?
Upvotes: 0