Question

I am currently working on a project in which I am retrieving data about names from the Social Security website. Basically I'm given a number x, and years y and z. I have to return the top x names from each of the years y through z.

So the data returned from the website is a name, a rank, and a year. I have to enter each name returned into either a TreeMap, HashMap, or LinkedHashMap, but I'm not sure how to store them, because no matter what I use as the key, there might be duplicates. The year cannot be the key as I will have the top x names from each year, so they would all be from the same year. If there are multiple years, there would be several names of rank 1, etc, as there is one for each year, so that could not be the key. And the name itself could not be the key as the same name might have been in the top several names for multiple years.

I've managed to understand most of the complicated parts of this project, yet this--one of the simplest parts, I can't seem to understand!

I've heard of ways that I can use something like the year as the key and make the value a list of names or something similar, but I'm not sure how I would add values in implementations like that. I would greatly appreciate any recommendations!

Thanks so much.

Edit: Please note that I was specifically told I MUST use TreeMap, HashMap, or LinkedHashMap. I've heard of MultiMap but that's not one of my options.

Was it helpful?

Solution

I think using a hashmap with an List is what you're specifically asking for. An example of how to instantiate such an object would be:

HashMap<Integer, List<String>> myHashMap = new HashMap<Integer, List<String>>();

Note that we have to use Integer because Hashmaps only work with objects. To add values to this, you could do:

myHashMap.get([whatever year you wanted]).add("[whatever name you want]");

However, a look at this question shows this would not be quite as easy as this, as you must instantiate each List for all your key's (that question deals specifically with multidimensional hashmaps, but the premise is the same). However, it is doable, as the answer to that question demonstrates. You should have a look at it, as I think it will you help you understand what's going on with all this, but the code that might work for you could look like (taken almost directly from the answer to the linked question):

if (!myHashMap.containsKey(myYear)) {
    myHashMap.put(myYear, new List<String>());
}

Edit: If you can't use the List inside either, I suppose you could put another hashmap inside, but I don't see that having much real use for this unless it's just an arbitrary requirement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top