获取HashMap值的计数数量 [英] get count number of HashMap value

查看:86
本文介绍了获取HashMap值的计数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the code from this link loading text file contents to 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的内容为:

In case of if contents of 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()计数存储在文本文件中的所有数据行.

Now I want to count the values in HashMap, but sections.size() counting all data line stored in text file.

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

I w'd like to ask how can I count the items, i.e. values v in sections? How can I get number 4, according to authors name?

推荐答案

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

Since the AUTHOR has a 1 to many relationship, you should map it to a List structure instead of a 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;
}

这篇关于获取HashMap值的计数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆