Doc Holiday
Doc Holiday

Reputation: 10254

Java- Adding unique values to Hashmap

ok,

here is my issue....I have a List<short>letterList which has for example: "1,2,3,4,5,6,7,8,9,10"

What Im doing is Im iterating over this list then passing the value into another method which returns a value:

so:

string value = null;
for(Short foo : letterList)

{
   value = getSomeValue(foo) //returns a letter A or B or C
}

What Im trying to do is get a hashmap to look something like this:

key: a, value 1,5,7
key b, value: 2,3,4
key c, value: 6,8,9,10

not these values specifically, but you get my point

Im not sure how to do this I have tried creating a map with a <set<string>, List<short>

any suggestions would be appreciated

Upvotes: 0

Views: 2449

Answers (4)

user
user

Reputation: 719

Java has no built-in MultiMap, but you can either simulate a multimap (Map<String, List<Short>>) or try out Guava for example: https://code.google.com/p/guava-libraries/

Upvotes: 1

rnk
rnk

Reputation: 2549

Not knowing your complete use case, I would suggest having a different look at your data structure organization. e.g.

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

Where the keys are 1,2....10 as in your example and the values are

1 -> a
2 -> b
3 -> b
etc. 

To get your original "list" you can use -

Set<Integer>  numbers = map.keySet();

Upvotes: 0

John Starich
John Starich

Reputation: 619

HashMap<Character, List<Short>> map

My understanding was you were looking for a simple way to store a list of values with a character? If so, use that above.

If you want to sort by letter (for easy printing out) use the following:

TreeMap<Character, List<Short>> map

You can get and of the values by using map.get('A') and using your standard methods to iterate through or get a certain value from the associated list.

Upvotes: 2

Xabster
Xabster

Reputation: 3720

Map<String, List<Short>>

The key (String) will be unique. The List<> will be able to hold a list of shorts.

If you want to make sure the numbers are unique as well as the keys, then use a Set instead of a list.

Remember to initialize the lists you put in the map (getting a key like "A" for the first time will return null, so check if it's null and if it is then create a List, put your value into it, and put the list into the map).

Upvotes: 0

Related Questions