5

The question sounds a bit weird but I can explain it: I have a HashMap filled with Strings as keys and values. And I have a String. Now I want to do something like that:

if(myhashmap.containskey(ANY PART OF MY STRING)

Like:

String str = "Java is cool!";
[HashMap that contains following : "Java";

I want that I can check if a String contains something. Maybe I could do that with a for loop but there is nothing like hashmap.entry. What would you do?

EmeldemelTV
  • 73
  • 1
  • 1
  • 9
  • 2
    Find a different data structure; use a for loop on the "parts" of your `String`; your `HashMap` is organized by the *`hashCode()`* of the key(s) in it. – Elliott Frisch Mar 06 '19 at 19:02
  • 3
    What do you mean by "any part of"? Do you mean any word in the string? Or any substring? Or something else? For example, if the key were `"va is co"`, would you expect your code to be able to find it? – Dawood ibn Kareem Mar 06 '19 at 19:06
  • you can iterate over the _keySet_, but is sound like you want a different data structure – Jocke Mar 06 '19 at 19:11

2 Answers2

6

You can loop over the keys of the map and check if they are in the string:

String str = "Java is cool!";
Map<String, ...> map = ...;

for (String key : map.keySet()) {
    if (str.contains(key)) {
        ...
    }
}

If you also need the associated value for the key, you can use entrySet.

Clashsoft
  • 11,553
  • 5
  • 40
  • 79
3

You can do it with stream and filtering, which is pretty functional :)

Map<String, Integer> map = new HashMap<>();
map.put("Hello World", 1);
map.put("Challo World", 2);
map.put("Hallo World", 3);
map.put("Hello Universe", 4);
map.put("Hello Cosmos", 5);

List<Integer> values =
    map.keySet().stream()
       .filter(key -> key.contains("World"))
       .map(map::get)
       .collect(Collectors.toList());

You should get a List<Integer> with values 1,2,3.

Hasasn
  • 810
  • 8
  • 9