2

What is the easiest way to get String Key from HashMap that contains some String fragment? Is true that only way is enumerate all keys and do substring()?

This pseudo code gets exact string, and I need string that only contains fragment.

Map hm= new HashMap();
...
res = hm.get("blabla");

I need to use java 1.4

vico
  • 17,051
  • 45
  • 159
  • 315
  • 1
    A-B problem. Better tell why do you need it. – AdamSkywalker Jan 13 '16 at 08:13
  • if you can use Common Collections, you may try http://tostring.me/287/partial-string-search-in-hashmap-key/, check also this other question http://stackoverflow.com/questions/6713239/partial-search-in-hashmap – BigMike Jan 13 '16 at 08:36

2 Answers2

2

Yes, you have to loop on all keys and search the substring you want.

HashMap.get will call equals, so for Strings, they must have the exact same content.

Arnaud
  • 17,229
  • 3
  • 31
  • 44
1

You have to either create a custom Data Structure or check each key individualy. The following returns a list:

Set ref = hm.keySet();
Iterator it = ref.iterator();
List list = new ArrayList(); // list contaning the deired elements

while (it.hasNext()) {
    Object o = it.next(); 
    if(hm.get(o).contains(value)) { 
        list.add(o); 
    } 
} 
Irina Avram
  • 1,492
  • 2
  • 20
  • 35