hub
hub

Reputation: 101

get count number of HashMap value

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"));

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

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

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?

Upvotes: 1

Views: 301

Answers (1)

Michael Markidis
Michael Markidis

Reputation: 4191

Since the AUTHOR has a 1 to many relationship, you should map it to a List structure instead of a String.

For example:

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

Upvotes: 2

Related Questions