开发者

HashMap: get arraylist to be a set of key or value

I have two arraylists A1, A2. Each element of A1 would be the key and each element of A2 the corresponding value. So the solution that I found is looping on A1 ( A1 and A2 have the same size) making hashmap.add(A1[i],A2[i]) but is there a w开发者_运维问答ay to directly send the key value pairs as two sets? I want to avoid loops it is going to slow my code..Thank you in advance!


"I want to avoid loops it is going to slow my code." Anytime code does anything, it slows down your code. The key is to avoid doing things you don't need to do. Something needs to iterate through your lists.


You have a list of key value pairs. The only way to take that list and add it into the Hashmap is to iterate the list. If you had your key value pairs stored in some other type of Map object then you could use the Hashmap constructor HashMap(Map<? extends K,? extends V> m) but not with your ArrayList.

Don't fear the iteration in your code if it is the right approach. Remember Polya: Find a solution, then see if you can find a better solution.


If you happen to be able to control the order in which you insert the items into the arrays, and you can do so in sorted order, you may not need the HashMap after all. While the hashed lookup will exhibit amortized constant time, you can get lookup in O(log n) time with binary search over a sorted random-access sequence like an array. Function Arrays#binarySearch() allows you to figure out which element, if any, matches your key in the first array and, given that position, you could the access the corresponding value in the parallel array.

This approach is most beneficial when you build up the data only once and look up entries frequently, and don't do any subsequent adding or removing of entries.


Maybe you would be able to avoid the iteration to insert the data into arrays doing it directly into the hashmap.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜