Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to initialize and fill final static ordered Map?

I have a stemming algorithm in Java which requires a static final HashMap<String, String> pre-filled with about 30 000 records.

I need the map to keep records in the same order they are inserted (I got a hint I could use LinkedHashMap?).

I thought I could manually insert the values in the Java class file since this is the quickest way to load them in RAM (time / productivity is very important for this project) by using 30 000 calls like

map.put("Key", "Value");

The problem is, that java (or at least eclipse) allows only 65kb of code in any segment / method etc. So I ended up extending 11 classes and putting 65kb of .puts in a constructor or a static { }.

Everything was fine, but when I run it the order is scrambled. For so many rows I cannot track where did things go wrong, in the extending order or in the map.

So, please tell me what is the best way you would fill a final map in java with regards to performance.

P.S.: Loading and parsing the records from a file is far too slow...

like image 810
Tony Bogdanov Avatar asked May 03 '26 10:05

Tony Bogdanov


2 Answers

Everything was fine, but when I run it the order is scrambled. For so many rows I cannot track where did things go wrong, in the extending order or in the map.

a) A HashMap doesn't preserve insertion order. Use a LinkedHashMap instead. Or, since you will use it as a constant, consider a Guava ImmutableMap. It preserves insertion oder, is immutable and provides a builder object for constructing it with many values.

b)

P.S.: Loading the records from a file is far too slow...

Why? It would only be done once, during class load time. And 35K String / String pairs is really not a lot of data for a modern machine.

like image 156
Sean Patrick Floyd Avatar answered May 05 '26 22:05

Sean Patrick Floyd


Have you considered to use in memory database?(e.g HSQLDB) It doesnt look right to pre-fill a class with so many data.

like image 31
Andy602 Avatar answered May 05 '26 23:05

Andy602



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!