• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can you search for a substring part of Hashmap value?  RSS feed

 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
given a HashMap that has <String, String> key-values, to see if a keyword matches the a value in the Map, I use something like

for Map:
Map<String, String> searchByName = new HashMap<String, String>();

find value:
if(searchByName.values().contains(keyword))


So, say the value is "frodo", but instead of the keyword being "frodo", can I peg the value with a partial keyword such as "odo"?
 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh, by keyword, I am not referring to the "Key" of the hashmap.... it's just a search criteria....
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ted Schrey wrote:given a HashMap that has <String, String> key-values, to see if a keyword matches the a value in the Map, I use something like

for Map:
Map<String, String> searchByName = new HashMap<String, String>();

find value:
if(searchByName.values().contains(keyword))


So, say the value is "frodo", but instead of the keyword being "frodo", can I peg the value with a partial keyword such as "odo"?


The Map interface does not directly support that, and neither does the returned Collection from Map.values. You will either have to iterate over the returned collection and do your own substring search, or if you're using Java 8 you can use Streams to do the same thing.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't call that a keyword. As you have already been told, no you cannot directly search for a V in a Map. You access things in Maps via the K. You can get bidirectional Maps; look up Apache Commons for an example you can use. You cannot directly search for a substring in such a bidirectional map either. At least I don't think you can. Maybe you are going to have to design your own type of Map.
 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, thank you . I ended up iterating entrySet and using the .contains() method on the values, then pulling the key from that.. thanks again for the help and advice!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!