简体   繁体   中英

Assigning values to Map (Hashmap or Multimap)

I have a map :

HashMap<String, ArrayList<Integer>> hashmap = new HashMap<String, ArrayList<Integer>>();

After retrieving data from a remote database server, I am creating a hashmap:(output in eclipse)

{newcomer=[23, 78, 118, 155, 240, 244], zoom=[213], profession=[8, 10, 12, 13, 15]}

Now, my concern is, it is taking too much of time to connect to server and download data. Size of data is beyond limit of my patience. Is there any way, I can store value directly in a Hashmap variable (like we do with normal variables, int i =5);

In general, how can I do this (like I do in Python) :

hashmap = {newcomer=[23, 78, 118, 155, 240, 244], zoom=[213], profession=[8, 10, 12, 13, 15]}

I have switched to Guava recently, Can I do this Multimap as well? Value I want to assign is now a string, so assigning might be much more complicated than I am thinking.

Edit 1 : I need this for development purpose only. Once application is live, will reconnect to database server.

Edit 2 : I have nearly 50k pairs at this moment, hence adding individually is not an option. May, for development, I can trim list to 100 items, but that too involve labor to put each one.

Edit 3 : I understand we can figure out someway or other to setup database more perfectly for fast execution. I only need to figure out that is it possible to assign? Else, I am going for local setup.

Inline initialization of Map s is not possible in Java. In your case this doesn't matter however -- with the amout of data you have populating the Map via code either means hours (or days) of highly repetetive and extremely error-prone manual typing or writing a code generator:

I have nearly 50k pairs at this moment, hence adding individually is not an option.

And if you write a code generator anyway, it doesn't matter if it generates an inline initializer or loads of Map#put() statements.

However, code generation / initialization in code certainly is a bad choice in this case anyway. Better solutions would be (sorted by decreasing usefulness):

  • Take care of your slow database setup or unoptimized query (see comment from CBass to the original question).
  • Take care to only load that data once, making the delay less relevant to the big picture.
  • Read it from the DB server once, then serialize it to a file (see ObjectOutputStream ) and deserialize it from there afterwards.
  • You could set up a local (fast) database server and read from that instead of the remote one.

I wouldn't even think of initializing a data structure of this size in code unless all the above things have been shown to not work. Which is extremely unlikely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM