[英]How to iterate through HashMap of Some Class and List of Classes in Freemarker
[英]How to iterate through List in a hashmap value
我有一個HashMap
其中String
作為鍵, List
作為值。
HashMap
名稱是pageMap
。
假設此pageMap
具有以下鍵和值:
key = order
value = [page1, page2, page3]
現在我要以以下模式顯示:
order
page1
page2
page3
key2
value1
value2
value3
value4
請告訴我該怎么做?
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));
}
}
實際上,解決方案非常簡單。
hashmap.get(key).iterator();
是給定鍵列表的迭代器。
為什么不嘗試自己弄清楚呢?
Iterate using iterator through all keys of hashmap using keyset()
{
print key
Iterate through value list using iterator
{
print each value
}
}
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
這與Jeppi的答案非常相似,但是使用字符串連接是我最喜歡Java的事情之一。 我還沒有運行任何基准測試,但是我猜想他會更快一些,但是我的開銷會更少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.