获取HashMap值的计数

使用此链接中的代码将文本文件内容加载到GUI:

Map sections = new HashMap(); Map 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()计算存储在文本文件中的所有数据行。

我想问一下如何计算项目,即sectionsv ? 根据作者的名字 ,我怎样才能得到4号?

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

例如:

 Map> sections = new HashMap<>(); Map 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 authors = null; if(sections.containsKey(k)) { authors = sections.get(k); } else { authors = new ArrayList(); 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; }