static HashMap<String, HashMap<String, List<Integer>>> BIGMAP= new HashMap<String, HashMap<String, List<Integer>>>();
这是一个 HashMap ,如果我将其打印出来,这就是我得到的:
SortedSet<String> keys = new TreeSet<String>(BIGMAP.keySet());
for (String key : keys) {
HashMap<String, List<Integer>> value = kmap.get(key);
System.out.println(key + " : " + value);
}
a.txt : {a=[20], to=[10]}
b.txt : {a=[4, 20], by=[16], is=[2], to=[13, 22]}
c.txt : {a=[15], as=[16, 17], in=[34], do=[9], to=[14]}
所以我试图迭代上面的“BIGMAP”,对于每个键 a.txt(String) 有一个 Value,它是另一个映射 HashMap<String, List<Integer>>
的结构
...
输出:
a [15],[20],[4, 20],
as [16, 17],, ,, ,
by , ,, ,[16],
...so on...
...so on...
...so on...
预期/想要的输出
a 20, 4:20 ,15
as , , 16:17
by , 16 ,
打印格式应该像上面一样,但显然它应该从每个文本文件(字符串)中按顺序打印,这是外部 HashMap 中的键
例如a 20, 4:20 ,15
“a”是那个词,20
来自 key 为 a.txt
的值和4:20
来自 b.txt
和15
来自 c.txt
正如你所看到的,我在那里有一些东西,但它并没有完全满足我的需要。当有多个数字时,冒号是必需的。有时可能是 4:20:50:92
最佳答案
这将在 Java 8 中完成这项工作。这不是我最好的工作,但使用您的示例值进行了成功测试。
BIGMAP.values()
.stream()
.flatMap(m -> m.keySet().stream())
.distinct()
.sorted()
.map(k -> k
+ " "
+ BIGMAP.entrySet()
.stream()
.sorted(comparing(Entry::getKey))
.map(e -> e.getValue()
.getOrDefault(k, Collections.emptyList())
.stream()
.map(String::valueOf)
.collect(joining(":")))
.collect(joining(", ")))
.forEachOrdered(System.out::println);
产生以下输出:
a 20, 4:20, 15 as , , 16:17 by , 16, do , , 9 in , , 34 is , 2, to 10, 13:22, 14
关于java - 访问Hashmap中的Hashmap,并以某种格式打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308733/