java - Partial search in HashMap -



java - Partial search in HashMap -

i need create phone book kind of thing. contains name & number. when type letters matching list should returned. illustration given below, when type h, list containing harmer, harris, hawken, hosler should returned. when type ha list containing harmer, harris, hawken should returned.

map<string, string> namenum = new hashmap<string, string>(); namenum.put("brown", "+1236389023"); namenum.put("bob", "+1236389023"); namenum.put("harmer", "+1236389023"); namenum.put("harris", "+1236389023"); namenum.put("hawken", "+1236389023"); namenum.put("hosler", "+1236389023");

any thought how accomplish it? in advance.

yeah, hashmap not right info construction this. bozho said, trie right one.

with java's on-board tools, treemap (or sortedmap, actually) used:

public <v> sortedmap<string, v> filterprefix(sortedmap<string,v> basemap, string prefix) { if(prefix.length() > 0) { char nextletter = prefix.charat(prefix.length() -1) + 1; string end = prefix.substring(0, prefix.length()-1) + nextletter; homecoming basemap.submap(prefix, end); } homecoming basemap; }

the output sorted key.

here usage example:

sortedmap<string, string> namenum = new treemap<string, string>(); // set phone numbers string prefix = ...; for(map.entry<string,string> entry : filterprefix(namenum, prefix).entryset()) { system.out.println(entry); }

if want prefix filter not depending on case differences, utilize suitable comparator map (like collator suitable strength setting, or string.case_insensitive_order).

java map filtering

Comments

Popular posts from this blog

java - How to pass parameters between Request-Scoped Controllers? -

string - what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++? -

actionscript 3 - Flex: moving a point with rotation doesnt change the point XY? -