Get a list of key's in HashMap having key like 'some value'

If you're using Java SE 8 and the new Streams API: there is a filter method which basically is what you are looking for, I think.

e.g. something like (untested!):

myMap.entrySet().stream().filter(entry -> entry.getKey().contains("someName")).map(entry -> entry.getValue()).collect(Collectors.toList());

You can iterate on all your keys and check if they match a regexp. This might not be the most efficient way of doing it, but it's the first thing I thought of. Here is what it would look like:

Pattern p = Pattern.compile("*someName*"); // the regexp you want to match

List<String> matchingKeys = new ArrayList<>();
for (String key : map.keySet()) {
    if(p.matcher(key).matches()) {
        matchingKeys.add(key);
    }
}

// matchingKeys now contains the keys that match the regexp

Note: map is supposed to be declared earlier like this:

HashMap<String, SomeValueClass> map = new HashMap<>();

Tags:

Java

Hashmap