Take the 2-minute tour ×

I declared a POJO class with id, Name, age, contactNumber and Address attributes. I declared all getters and setters. Now I am using HashMap<String, POJO_CLASS>. By default I sorts these values by Name attribute. Now my need is to search an object by id, and that method should return an object (which is stored in HashMap as value). So how can I use Collections.binarySearch() for this requirement.

share|improve this question
Is this about efficiently finding the object by id, or specifically about binarySearch? –  NPE Mar 2 '11 at 16:50
What's the type of id, and what field of your object are you using as the key of your map? –  tgdavies Mar 2 '11 at 17:05
Actually I have more than 500 objects of my POJO class, and I have to search an object by id, so thought this will be best way. Is any other way? Please guide me if other way exists. –  Pankaj Kumar Mar 2 '11 at 17:08
Also what do you mean when you say you sort these values by name? HashMaps don't sort their contents. –  tgdavies Mar 2 '11 at 17:20
add comment

3 Answers

up vote 1 down vote accepted

The better question is why would you want to. HashMap lookups are going to be very fast, O(1) time whereas binary searches are going to take O(lg(N)) time on Lists that have random access abilities (ArrayList).

If you really want to use binary searches then you need to store your objects in a list (ArrayList probably) and have that list sorted and then call Collections.binarySearch(list, value).

share|improve this answer
add comment

500 objects is not that many, so I would just put them in a second HashMap keyed on the id.

share|improve this answer
add comment

If you need fast lookup by both name and by id, you're going to need to permanently store the POJOs in two different data structures. In this case, building a second HashMap off of id, would give you the best performance.

This may be unnecesarily complex if the map is not that large or lookup by id is a relatively infrequent occurance. In that case I would just do a linear search through the HashMap.

share|improve this answer
add comment

Your Answer


