mavix
mavix

Reputation: 2572

Best way to create a table of data, and how to initialize it?

I want to create a table with String keyvalues and integer data. Right now I am leaning towards creating a two-dimensional HashMap:

HashMap<String, HashMap<String, Integer>>

Is that going to be my fastest and most flexible option? I am using it to create a language model so there will be a lot of changes and frequent lookups. Also, is that the correct syntax? And how would I initialize it?

new HashMap<String, new HashMap<String, Integer>> 

seems wrong to me for some reason but I can't place why.

Upvotes: 0

Views: 480

Answers (5)

Marat Salikhov
Marat Salikhov

Reputation: 6627

Just for the record: Google Guava Table

Google Guava is a quite handy library containing many useful collection and utility classes.

Upvotes: 1

Keith Randall
Keith Randall

Reputation: 23265

You could also define your map like this:

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

Where Pair has a reasonable definition (don't forget equals and hashCode!).

This is simpler (insert doesn't have to check whether the sub-map is created or not) and probably faster (only 1 hash lookup instead of 2).

If you know of some character that can't be in either of your strings, then you could just use String instead of Pair<String> where the key is the concatenation of the two keys with that character as a separator.

Upvotes: 2

Steven You
Steven You

Reputation: 459

Hash Map is fast and flexible, but may consume more memory. The define syntax is correct, for initialization:

HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> record = new HashMap<String, Integer>();
record.put("key", 42);
map.put("key", record);

Upvotes: 0

Paul
Paul

Reputation: 1088

Maps would definitely work.

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

// Put a new "row" in the column "some_col"   
myTable.put("some_col", new HashMap<String, Integer>());

// put a value into some_col and some_row
myTable.get("some_col").put("some_row", 9);

// Get a value from some_col and some_row
Integer val = myTable.get("some_col").get("some_row");

Upvotes: 0

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

This syntax new HashMap<String, new HashMap<String, Integer>> is not correct.

You can do this

map = new HashMap<String, Map<String, Integer>>;
map.put("key", new HashMap<String, Integer>());

I.e. for each key you need to put a new sub-map instance.

Upvotes: 0

Related Questions