【问题标题】:get count number of HashMap value获取 HashMap 值的计数
【发布时间】:2016-05-18 06:13:40
【问题描述】:

使用来自 link 的代码将文本文件内容加载到 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的if内容:

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

我想问一下如何计算项目,即sections 中的值v?如何根据作者姓名获得编号4

【问题讨论】:

    标签: java java-io


    【解决方案1】:

    由于 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;
    }
    

    【讨论】:

    • 感谢您的回复,现在计数工作正常,但我不能setTextjTextField1 jTextField1.setText(sections.get("AUTHOR"));
    • 如果要将列表转换为字符串,则只需循环遍历列表并根据需要连接字符串。我将在我的帖子中展示一个示例。
    • 谢谢。我很高兴能提供帮助。
    • 我想问一个与numOfAuthors相关的问题,我想用它来jButton1.doClick(numOfAuthors);,但是它不能正常工作,我不明白为什么。跨度>
    • 我不确定你想在那里做什么,因为 doClick() 方法不接受任何参数。我会将其作为另一个问题与相关代码以及您遇到的错误一起发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多