Search code examples
javaarrayshashmap

Using HashMap to count the quantity of certain integers from an array


I have an array that looks like this: values consisting of 14 integers

String[] helloarray = new String[]
{"30","31","32","33","34","35","36","37","38","39","60","61","62","63"};

Using an hashmap as below:

Map<String, Integer> hellocnt  = new HashMap<String,Integer>();

The goal is to find the occurrence or find the total quantity of each of these integers that exist in the file?

// using bufferedreader to read and extract the lines
// and integers from the file and storing it in intvalue
String temp[] = line.split(" ");
for (i = 0; i < temp.length; i++) {
    String intvalue = temp[i];
}

Now I need to match how many times/quantity of each integer exists in the file (intvalue)

int e = 0;
for (e = 0; e < helloarray.length; e++) {
    if (intvalue.contains(helloarray[e])) {
        System.out.println("found: " + helloarray[e]);
        if (helloarray[e] == "32") {
            // Should I use the hashmap here since I don't want to use
            // MULTIPLE IF BLOCKS checking for each integers and want 
            // to reuse the same map function and store the incremented 
            // counter after the completion?
        }
    }
}

Please suggest an optimized less brute force method to achieve it?


Solution

  • The way to do it is as follows.

    1. After setting up the array and map like so:
    String[] helloarray = new String[]
            {"30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "60", "61", "62", "63"};
    Map<String, Integer> hellocnt = new HashMap<String, Integer>();
    for (String str : helloarray)
        hellocnt.put(str, 0);
    
    1. For each line that you read:
    String temp[] = line.split(" ");
    for (i = 0; i < temp.length; i++) {
        String intvalue = temp[i];
        if (hellocnt.containsKey(intvalue)) {
            hellocnt.put(intvalue, hellocnt.getOrDefault(intvalue, 0) + 1);
        }
    }
    
    1. You can then view the contents of the map simply by doing:
    System.out.println(hellocnt);