这将进行转换。代码看起来很复杂,但总体复杂度仍然是 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) 并且我们不能更有效地做到这一点,因为我们必须访问每个键/值对一次才能打印它。
(除非我们可以使用并行计算;))