MAY3AM
MAY3AM

Reputation: 1212

Best way to store and search through large list of key, value

I'm going to create a java class for android project that give number and return regional name based on phone code ( it's for Local use)

Our phone numbers length is between 8 and 10, regional code length is 4 or 5.

  1. whats the best way to store regional codes? Is HashMap<Integer, String> suitable for this reason <region code, region name>? ( data for each city could be til 200 records)

  2. whats the best way to search through this? As I said earlier regional code length could be 4 or 5, then we should search at the first time between 4 digit and then if there was no any result search 5 digits?

Upvotes: 0

Views: 298

Answers (2)

BlackHatSamurai
BlackHatSamurai

Reputation: 23503

Using a hashmap is going to be your best bet. It has a run time of O(1), so when searching for a key, so you can do something like:

HashMap<String, Integer> hm = new HashMap<String, Integer>();
hm.put("yourKey", 12345);
...//repeat as needed
hm.get("yourKey");

And that will be the quickest way to get your value. If the value exists, it will return the mapped value, otherwise it will return null if there is no mapping. The length of the key is irrelevant.

Upvotes: 1

ravip
ravip

Reputation: 101

Yeah. You can use HashMap to store the data. After storing the data by using the keySet() method of HashMap you will get the list of all keys as a sorted(ascending) set.

After that using the contains() method of Set, You will know the region code exists or not irrespective of 4 or 5 digits ( Else you can try first 4 digits if it returns false then you can try 5 digits).

By submitting that key(region code) to your Map you will get the region name easily.

Upvotes: 1

Related Questions