這將做轉型。代碼看起來很複雜,但總體複雜性仍然是O(n):無論地圖的大小如何,每個鍵和值都會觸及固定次數。
public static void main(final String[] args) {
Map<String, String> map = getMap();
Map<String, String[]> map2 = new TreeMap<>();
// (1) Read the map into an intermediate map and
// get the number of rows needed
int maxSize = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
String[] array = entry.getValue().split(",");
maxSize = array.length > maxSize ? array.length : maxSize;
map2.put(entry.getKey(), array);
}
// (2) prepare the table structure
List<List<String>> table = new ArrayList<>();
for (int i = 0; i < (maxSize + 1); i++) {
table.add(new ArrayList<String>());
}
// (3) read the values into the table structure
for (Map.Entry<String, String[]> entry : map2.entrySet()) {
table.get(0).add(entry.getKey());
for (int i = 0; i < maxSize; i++) {
if (i < entry.getValue().length) {
table.get(i + 1).add(entry.getValue()[i]);
} else {
table.get(i + 1).add("");
}
}
}
// (4) dump the table
for (List<String> row : table) {
StringBuilder rowBuilder = new StringBuilder();
boolean isFirst = true;
for (String value : row) {
if (isFirst) {
isFirst = false;
} else {
rowBuilder.append('|');
}
rowBuilder.append(value);
}
System.out.println(rowBuilder.toString());
}
}
private static Map<String, String> getMap() {
Map<String, String> map = new TreeMap<>();
map.put("key1", "1,2,3,4");
map.put("key2", "5,6");
map.put("key3", "7,8,9");
return map;
}
此示例的結果是:
key1|key2|key3
1|5|7
2|6|8
3||9
4||
(第一應答的基礎上,錯誤猜測)
假設,5和6是值爲鍵 1和2,那麼這是一個很好的解決方案:
public static void dumpMap(Map<String, String> map) {
for (Map.Entry<String, String> entry:map.entrySet()) {
System.out.printf("%s|%s%n", entry.getKey(), nullSafe(entry.getValue()));
}
}
private static String nullSafe(String value) {
return value == null ? "" : value;
}
這是O(n),我們不能做得更有效率,因爲我們必須訪問每個鍵/值對來打印一次。
(除非我們可以使用並行計算;))
你的問題不清楚 - 請澄清輸入是什麼。 (你的標題說地圖,但是'key1:1,2,3,4 key2:5,6'看起來不像一個)。 – assylias
你剛剛擁有兩把鑰匙嗎? –
這可能是一個'Map>'? –