blekione
blekione

Reputation: 10590

Is there a better way to implement search map?

I have a map of objects Members

public class Member {

int id;
String firstName;
String lastName;
String street;
String city;
...

with id as a key, which is doing job for me and I don't want to change structure of the map.

I need to implement search by name functionality. So far I can think only about 2 solutions:

1st is to iterate trough the map - not most time efficient way

2nd is to create another map with member's names as a keys and ids as values as reference to my main map and search trough this map to find the key - efficient with time but less in space, which not worry me too much

I want to ask if there is more efficient (better) way to implement search of map in my case?

Upvotes: 1

Views: 65

Answers (2)

Eran
Eran

Reputation: 393966

There's no point in creating a second Map if it would require 2 lookups (first find the id for a given name and then find the Member of that id).

It would be more efficient if the second Map would map the name keys to the Member values (i.e Map<String,Member>). You might be thinking that such an approach would require more memory compared to a Map<String,Integer>, but you would be wrong. A reference to a Member instance takes the same amount of memory as a reference to an Integer instance. Just because you have two Maps that contain the same values, doesn't mean that the Member instances need to be duplicated. Only the references to those isntance would be duplicated.

Upvotes: 3

rgettman
rgettman

Reputation: 178303

You're right that iterating through the map is not the most efficient way; that will be O(n) with n Members.

You're on the right track with creating a second Map keyed by the members' names. What I would change is have the Member references as the values for this second map too, so that you don't have to retrieve the ID then perform a second lookup on the first map to retrieve the Member. This would be a Map<String, Member>.

Upvotes: 6

Related Questions