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?
3
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
.
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.