簡體   English   中英

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}

因此,它會查找具有完全匹配或以其開頭的鍵的所有值。
有什么建議? 如果有可用的東西或我可以寫點什么?
謝謝!

您可以使用tailMap方法使用TreeMap<String,Integer>執行此操作,並在鍵與輸入匹配時迭代結果:

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());
}

演示。

使用TreeMap,創建一個特殊的迭代器,映射到TreeMap並搜索您要查找的字符串模式

在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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM