获取HashMap中的键列表,其中包含"some value"之类的键

ach*_*uth 6 java hashmap

在Mysql中我们可以查询具有子句" WHERE name LIKE'%someName%' "的表,我们可以在java中使用与HashMap相同的功能,如果是这样的话,我们如何通过不迭代每个元素在更短的时间内更有效地实现这一功能?

Puc*_*uce 5

我认为,如果您使用的是Java SE 8和新的Streams API:有一种基本上是您所需要的过滤方法。

例如:(未经测试!):

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


Jof*_*rey 4

您可以迭代所有键并检查它们是否与正则表达式匹配。这可能不是最有效的方法,但这是我想到的第一件事。它看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

注意:map应该像这样提前声明:

HashMap<String, SomeValueClass> map = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)