我正在寻找更好的算法来通过其键以表格格式打印LinkedHashMap。
我在这里解释情况
//hashmap goes like this
LinkedHashMap<String , ArrayList<String>> hash=new LinkedHashMap<String,ArrayList<String>>();
// put some values in some arraylist
ArrayList<String> value1=Arrays.asList("s1", "s2", "s3");
ArrayList<String> value2=Arrays.asList("s4", "s5", "s6");
ArrayList<String> value1=Arrays.asList("s7", "s8", "s9");
// put values in hashmap
hash.put("key1",value1);
hash.put("key2",value2);
hash.put("key3",value3);
现在,我希望在
html
表中的输出应该像这样。key1 key2 key3
s1 s4 s7
s2 s5 s6
s3 s6 s9
什么是这样做的好方法?谢谢 。
最佳答案
以下代码应该做
public static void main(String[] args) {
// hashmap goes like this
LinkedHashMap<String, List<String>> hash = new LinkedHashMap<String, List<String>>();
// put some values in some arraylist
List<String> value1 = (List<String>) Arrays.asList("s1", "s2", "s3");
List<String> value2 = (List<String>) Arrays.asList("s4", "s5", "s6");
List<String> value3 = (List<String>) Arrays.asList("s7", "s8", "s9");
// put values in hashmap
hash.put("key1", value1);
hash.put("key2", value2);
hash.put("key3", value3);
int count = 0;
boolean exit = false;
while (!exit) {
for (String key : hash.keySet()) {
String value = hash.get(key).get(count);
System.out.printf("\t" + value);
}
System.out.printf("\n");
count++;
if (count == hash.get("key1").size()) {
exit = true;
}
}
}
以下是所需的输出:
s1 s4 s7
s2 s5 s8
s3 s6 s9