获取HashMap值的count个数

2024-03-25

使用这里的代码link https://stackoverflow.com/questions/37129625/read-and-find-string-from-text-file将文本文件内容加载到 GUI:

Map<String, String> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    while ((s = br.readLine()) != null) {
        String k = s.substring(0, 10).trim();
        String v = s.substring(10, s.length() - 50).trim();
        if (k.equals(""))
            k = lastKey;
        if(sections.containsKey(k))
            v = sections.get(k) + v; 
        sections.put(k,v);
        lastKey = k;
    }
} catch (IOException e) {
}
System.out.println(sections.get("AUTHOR"));
System.out.println(sections2.get("TITLE"));

如果是 input.txt 的内容:

AUTHOR    authors name
          authors name
          authors name
          authors name
TITLE     Sound, mobility and landscapes of exhibition: radio-guided
          tours at the Science Museum

现在我想统计HashMap中的值,但是sections.size()计算文本文件中存储的所有数据行。

我想问一下如何计算项目,即值v in sections?我怎样才能得到号码4, 根据作者姓名?


由于 AUTHOR 具有一对多关系,因此您应该将其映射到List结构而不是String.

例如:

Map<String, ArrayList<String>> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    while ((s = br.readLine()) != null) {
        String k = s.substring(0, 10).trim();
        String v = s.substring(10, s.length() - 50).trim();
        if (k.equals(""))
            k = lastKey;

        ArrayList<String> authors = null;
        if(sections.containsKey(k))
        {
            authors = sections.get(k);
        }
        else
        {
            authors = new ArrayList<String>();
            sections.put(k, authors);
        }
        authors.add(v);
        lastKey = k;
    }
} catch (IOException e) {
}

// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();

// convert the list to a string to load it in a GUI
String authors = "";
for (String a : sections.get("AUTHOR"))
{
    authors += a;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取HashMap值的count个数 的相关文章

随机推荐