繁体   English   中英

如何在Java中创建哈希图的哈希图?

[英]How can I create hashmap of hashmap in java?

我有一些文件。 例如1000个文档。 每个文档都有一些单词。 例如

Doc 1:你好,我来自地球

Doc 2:你好,我来自火星,你好

Doc 2:地球火星太阳

输出应该是这样的

[您好:doc1-1,doc2-2,doc3-0] [I:doc1-1,doc2-1,doc3-0] .....

就像它需要存储单个单词及其与文档相关的频率。

我想这需要映射。 但是我不知道该怎么做? 任何帮助将不胜感激

似乎并不需要Hashmap's HashMap 确实,您只需要一个Map ,其中的键是String ,而ValueCollection 您可以自己创建此抽象,也可以使用诸如Google Guava的 MultiMap之类的东西。

或者,您可以使用Lucene之类的方法,而无需编写所有这些代码,而无需从头开始编写查询文档。

尝试这个。

String[] files = { "doc1", "doc2", "doc3" };
int size = files.length;
Map<String, Map<String, Long>> result = new HashMap<>();
for (int i = 0; i < size; ++i) {
    Path path = Paths.get(files[i]);
    Map<String, Long> count = Files.readAllLines(path).stream()
        .flatMap(line -> Stream.of(line.split("\\s")))
        .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
    for (Entry<String, Long> e : count.entrySet()) {
        Map<String, Long> m = result.get(e.getKey());
        if (m == null)
            result.put(e.getKey(), m = new TreeMap<>());
        m.put(files[i], e.getValue());
    }
}
for (int i = 0; i < size; ++i)
    for (Map<String, Long> e : result.values())
        e.compute(files[i], (k, v) -> v == null ? 0 : v);
for (Entry<String, Map<String, Long>> e : result.entrySet())
    System.out.println(e);

结果:

Earth={doc1=1, doc2=0, doc3=1}
how={doc1=0, doc2=1, doc3=0}
Mars={doc1=0, doc2=1, doc3=1}
Hello={doc1=1, doc2=2, doc3=0}
I={doc1=1, doc2=1, doc3=0}
from={doc1=1, doc2=1, doc3=0}
am={doc1=1, doc2=1, doc3=0}
sun={doc1=0, doc2=0, doc3=1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM