我想在地图中找到带有模式匹配的键。
Ex:-
Map<String, String> map = new HashMap<String, String>();
map.put("address1", "test test test");
map.put("address2", "aaaaaaaaaaa");
map.put("fullname", "bla bla");
从上面的地图中,我想获得前缀为“address”的键的值。因此,在此示例中,输出应该是前两个结果(“address1”和“address2”)。
如何动态实现这一目标?
感谢。
答案 0 :(得分:18)
您可以抓取地图的keySet
,然后过滤以仅获取以“地址”开头的键,并将有效密钥添加到新的设置中。
使用Java 8,它不那么冗长:
Set<String> set = map.keySet()
.stream()
.filter(s -> s.startsWith("address"))
.collect(Collectors.toSet());
答案 1 :(得分:8)
如果你有Java 8功能,那么这样的东西应该有效:
Set<String> addresses = map.entrySet()
.stream()
.filter(entry -> entry.getKey().startsWith("address"))
.map(Map.Entry::getValue)
.collect(Collectors.toSet());
答案 2 :(得分:5)
这样的事情:
for (Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().startsWith("address")) {
// do stuff with entry
}
}
答案 3 :(得分:2)
您必须循环键集并匹配模式
for(String key : map.keySet()) {
if(! key.startsWith("address")) {
continue;
}
// do whatever you want do as key will be match pattern to reach this code.
}
答案 4 :(得分:1)
我创建了一个界面......
import java.util.Map;
@FunctionalInterface
public interface MapLookup {
<V> List<V> lookup(String regularExpression, Map<String,V> map);
}
实施
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class MapLookupImpl implements MapLookup {
@Override
public <V> List<V> lookup(String regularExpression, Map<String, V> map) {
final Pattern pattern = Pattern.compile(regularExpression);
List<String> values = map.keySet()
.stream()
.filter(string -> pattern.matcher(string).matches())
.collect(Collectors.toList());
if(values!= null && !values.isEmpty()){
return values.stream().map((key) -> map.get(key)).collect(Collectors.toList());
}
return new ArrayList<>();
}
}
测试
public static void main(String[] args){
Map<String, Integer> map = new HashMap<>();
map.put("foo",3);
map.put("bar",42);
map.put("foobar",-1);
MapLookup lookup = new MapLookupImpl();
List<Integer> values = lookup.lookup("\\woo\\w*",map);
System.out.println(values);
}
结果
[-1, 3]
或许那太过分了。不过,我可以看到重复使用它。
对于那些想要pre-java8版本的人:
public class PreJava8MapLookup implements MapLookup {
@Override
public <V> List<V> lookup(String regularExpression, Map<String, V> map) {
Matcher matcher = Pattern.compile(regularExpression).matcher("");
Iterator<String> iterator = map.keySet().iterator();
List<V> values = new ArrayList<>();
while(iterator.hasNext()){
String key = iterator.next();
if(matcher.reset(key).matches()){
values.add(map.get(key));
}
}
return values;
}
}
答案 5 :(得分:1)
我遇到了类似的需求,并试图为这样的数据结构实现POC。我得出结论,以某种方式对数据进行分区更加实用:)
但是,如果你真的有想法实现类似的东西,你需要一个更类似于特里树的结构。这是我得到的(我的道歉,因为代码在Scala中,但它很容易适应,如果你把它放在心上,你可以完成它并使其可用)
package component.datastructure
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
class RegExpLookup[T] {
private val root = new mutable.HashMap[Char, Node]
def put(key: String, value: T): Unit = {
addNode(key.toCharArray, 0, root, value)
println(root.toString)
}
private def addNode(key: Array[Char], charIdx: Int,
currentRoot: mutable.Map[Char, Node], value: T): Unit = {
if (charIdx < key.length - 1) {
if (currentRoot.contains(key(charIdx))) {
addNode(key, charIdx + 1, currentRoot(key(charIdx)).nodeRoot, value)
} else {
val node = Node(null, new mutable.HashMap[Char, Node])
currentRoot.put(key(charIdx), node)
addNode(key, charIdx + 1, node.nodeRoot, value)
}
} else {
currentRoot.put(key(charIdx), Node(value, null))
}
}
private def getAll(lastNode: Node, buffer: ArrayBuffer[T]): Unit = {
if (lastNode.value != null)
buffer.append(lastNode.value.asInstanceOf[T])
if (lastNode.nodeRoot != null)
lastNode.nodeRoot.values.foreach(e => {
getAll(e, buffer)
})
}
def get(key: String): Iterable[T] = {
val t = findLastNode(key.toCharArray, 0, root)
println("getting from " + root)
val isLast = t._2
if (isLast) {
val v = t._1.value
if (v != null)
return List(v.asInstanceOf[T])
else
return null
} else {
val buffer = new ArrayBuffer[T]()
getAll(t._1, buffer)
return buffer.toList
}
}
private def findLastNode(key: Array[Char], charIdx: Int,
root: mutable.Map[Char, Node]): (Node, Boolean) = {
if (charIdx < key.length - 2 && (key(charIdx + 1) != '*')) {
return (root(key(charIdx)), false)
} else if (charIdx < key.length - 1) {
return findLastNode(key, charIdx + 1, root(key(charIdx)).nodeRoot)
} else
return (root(key(charIdx)), true)
}
}
case class Node(value: Any, private[datastructure] val nodeRoot: mutable.HashMap[Char, Node]) {
}
基本上我们的想法是在后续地图中查找每个字符,复杂性现在是密钥的长度。实际上,这应该是一个可以接受的限制,因为reg ex的汇编很可能是O(N)。此外,如果你有更短的键,许多条目会产生更好的性能,然后迭代所有的键。如果你将mutable.HashMap与某种自己的实现交换为巧妙的散列,并利用一个字符实际上是一个int的事实,并且在ASCII字符串(可能是关键字)的情况下实际上是短的。如果你正在查找一些更复杂的表达式,那么也会更加困难*,但仍然可能。
编辑:测试
class MySpec extends PlaySpec {
val map = new RegExpLookup[String]()
"RegExpLookup" should {
"put a bunch of values and get all matching ones" in {
map.put("abc1", "123")
map.put("abc2", "456")
map.put("abc3", "789")
val result = map.get("abc*")
println(result)
val s = result.toSet
assert(s.contains("123"))
assert(s.contains("456"))
assert(s.contains("789"))
}
"put a single value and get it by exact key" in {
map.put("abc", "xyz")
val result = map.get("abc")
println(result)
assert(result.head.equals("xyz"))
}
}
}
答案 6 :(得分:0)
如果您不需要很高的性能,浏览地图上的所有按键(map.entrySet
)以获得与您的模式匹配的按键就足够了。
如果您需要良好的性能,我用来解决此类问题的解决方案是使用内存数据库,例如H2:您将数据放入内存表,在密钥上创建唯一索引,您将获得2个案例的良好表现:
select value from in_mem_table where key = ?'
)关联的值,hashmap的经典用法select value from in_mem_table where key like 'adress%'
)答案 7 :(得分:0)
一种方法是创建一个函数,在所有映射中搜索以地址开头的键,但这会消除映射的优势,因为目标可能很快。 另一种方法是创建一个包含以地址开头的所有键的列表或数组,但只有当你只想要以地址开头的键时才有价值。
现在你需要能够搜索任何东西或只搜索特定的东西吗?你需要地图还是像数组或列表那样的其他东西?