java 键值对,键查找为 "startswith"

java key-value pair with key lookup as "startswith"

我正在寻找一个集合来存储键值对,其中值应该根据键 startswith 条件返回。
例如对于给定的集合:(a,123) (ab,234) (abcd,5434)

如果我做 map.get(a) 它应该给我 {123,234,5434} 的数组,同样如果我做 map.get(ab) 它应该给我 {234,5434} 而不是 {123}在这种情况下。

因此,它会查找具有完全匹配的键或以其开头的所有值。
有什么建议么?如果有可用的东西或者我可以写点东西吗?
谢谢!

使用 TreeMap,并创建一个特殊的迭代器来映射您的 TreeMap 并搜索您正在寻找的字符串模式

您可以通过 TreeMap<String,Integer> 使用 tailMap 方法,并在键与输入匹配时迭代结果:

TreeMap<String,Integer> map = new TreeMap<String,Integer>();
map.put("a", 123);
map.put("ab", 234);
map.put("abcd", 5434);
String myKey = "ab";
for (Map.Entry<String,Integer> e : map.tailMap(myKey).entrySet()) {
    if (!e.getKey().startsWith(myKey)) {
        break;
    }
    System.out.println(e.getValue());
}

Demo.

对 dasblinkenlight 的解决方案稍作修改: Java 8 流 API 提供了一个很好的循环:

    TreeMap<String,Integer> map = new TreeMap<String,Integer>();
    map.put("a", 123);
    map.put("ab", 234);
    map.put("abcd", 5434);
    String myKey = "ab";

    Collection<Integer> matchValues = map.tailMap(myKey).entrySet()
        .stream()
        .filter(e -> e.getKey().startsWith(myKey))
        .map(e -> e.getValue())
        .collect(Collectors.toList());

根据 slanec 的评论,我查看了 Apache Commons Collections4 中的 PatriciaTrie,它确实有一种方法可以完全满足 OP 的要求:

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

Trie<String,Integer> t = new PatriciaTrie<>();
t.put("a", 123);
t.put("ab", 234);
t.put("abcd", 5434);
System.out.println(t.prefixMap("ab").values());