包含hashmap键中的操作

时间:2015-03-29 09:49:14

标签: java hashmap

我的hashmap包含一个条目**key: its-site-of-origin-from-another-site@@NOUN** and **value: its@@ADJ site-of-origin-from-another-site@@NOUN**

我希望仅根据“"其来自另一个网站的原始网站" ”的关键部分来获取此密钥的价值

如果hashmap包含类似'其原始网站来自另一个网站的密钥'那么它应该首先选择它的'然后是“来自另一个地方的原始网站”。只有在' @@'

之后的部分才会出现

2 个答案:

答案 0 :(得分:0)

没有。这将是一个字符串,所以它会在" @@"同样。如果您需要基于子字符串的值,则必须迭代地图,如:

String value = map.get("its...");
if (value  != null) {
    //exact match for value
    //use it
} else {//or use map or map which will reduce your search time but increase complexity
    for (Map.Entry<String, String> entry : map.entrySet()) {
        if (entry.getKey().startsWith("its...")) {
            //that's the value i needed.
        }
    }
}

答案 1 :(得分:0)

您可以考虑使用Patricia trie。它是一个类似TreeMap的数据结构,其中键是String和任何类型的值。它是存储的最佳选择,因为密钥之间的公共字符串前缀是共享的,但您的用例感兴趣的属性是您可以搜索特定的前缀并获取已排序的视图地图条目。

以下是Apache Common实施的示例。

import org.apache.commons.collections4.trie.PatriciaTrie;

public class TrieStuff {

    public static void main(String[] args) {
        // Build a Trie with String values (keys are always strings...)
        PatriciaTrie<String> pat = new PatriciaTrie<>();

        // put some key/value stuff with common prefixes
        Random rnd = new Random();
        String[] prefix = {"foo", "bar", "foobar", "fiz", "buz", "fizbuz"};
        for (int i = 0; i < 100; i++) {
            int r = rnd.nextInt(6);
            String key = String.format("%s-%03d@@whatever", prefix[r], i);
            String value = String.format("%s@@ADJ %03d@@whatever", prefix[r], i);
            pat.put(key, value);
        }

        // Search for all entries whose keys start with "fiz"
        SortedMap<String, String> fiz = pat.prefixMap("fiz");
        fiz.entrySet().stream().forEach(e -> System.out.println(e));
    }
}

打印以&#34; fiz&#34;开头的所有键。并排序。

fiz-000@@whatever
fiz-002@@whatever
fiz-012@@whatever
fiz-024@@whatever
fiz-027@@whatever
fiz-033@@whatever
fiz-036@@whatever
fiz-037@@whatever
fiz-041@@whatever
fiz-045@@whatever
fiz-046@@whatever
fiz-047@@whatever
fizbuz-008@@whatever
fizbuz-011@@whatever
fizbuz-016@@whatever
fizbuz-021@@whatever
fizbuz-034@@whatever
fizbuz-038@@whatever