Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在哈希映射中搜索特定模式_Java - Fatal编程技术网

Java 在哈希映射中搜索特定模式

Java 在哈希映射中搜索特定模式,java,Java,我有下面的片段。我需要找出是否有任何与折扣模式搜索地图键。帮助欣赏 public class MapStringSearch { public static void main(String[] args) { Map test = new HashMap(); test.put("discount.1", 1); test.put("discount.2", 2); test.put("discount.3", 3);

我有下面的片段。我需要找出是否有任何与折扣模式搜索地图键。帮助欣赏

public class MapStringSearch {

    public static void main(String[] args) {

        Map test = new HashMap();
        test.put("discount.1", 1);
        test.put("discount.2", 2);
        test.put("discount.3", 3);
        test.put("voucher.4", 4);

    }

}
其中一个方法是:

for ( String key : test.keySet() ) {
    if(key.contains("discount"))
      // do something...
    else
      // do something...
}
我倾向于这样做:

discount.put("1", 1);
discount.put("2", 2);
discount.put("3", 3);

test.put("discounts", discount);
因此,要找到折扣:

test.get("discounts");
在此之后,您可以使用keyset(或entryset)进行迭代,或者使用get


当然,您可以迭代关键点集,但要诚实;我会重新定义我的应用程序的de数据模式,以便在hashmap中不包含“something.[0-9]”元素。

我会使用SortedMap而不是hashmap,并检查tailMap(“折扣”).firstKey().stratsWith(“折扣”)

您已经展示了一个将条目放入地图的示例(使用原始类型,顺便说一句,这不是一个好主意),但你还没有解释你想要实现什么。“带折扣的模式搜索”是什么意思?提示:它需要方法
test.keySet()
,一个for循环来遍历键,一个if语句和一些其他代码…可以执行您想要执行的操作。。。但效率不高。想要这样做是。。。特有的作为一种实现您真正想要做的事情的方法,它可能是有缺陷的。@Raedwald:也许我错了,但我的问题是,假设我们在映射中有多个键,是否有任何API或基于模式的键搜索,只需将键作为输入并返回哈希映射,如果存在API,我只是避免在代码中进行迭代。
Iterator it = test.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println(pairs.getKey().toLowerCase().contains("YourString"))
}