簡體   English   中英

從java中的HashMap返回通配符匹配列表

[英]Returning a list of wildcard matches from a HashMap in java

我有一個Hashmap,可能在String中包含通配符(*)。

例如,

HashMap<String, Student> students_;

可以將約翰*作為一把鑰匙。 我想知道JohnSmith是否匹配student_中的任何元素。 我的字符串可能有幾個匹配(John *,Jo * Smith等)。 有什么方法可以從我的HashMap中獲取這些匹配的列表嗎?

是否有另一個我可能正在使用的對象,它不需要我遍歷我的集合中的每個元素,或者我是否必須將它吸收並使用List對象?

僅供參考,我的收藏品中將包含少於200個元素,最終我希望找到與最少量通配符匹配的對。

您可以使用正則表達式進行匹配,但必須首先將"John*"轉換為正則表達式"John.*" ,盡管您可以即時執行此操作。

以下是一些可行的代碼:

String name = "John Smith"; // For example
Map<String, Student> students_ = new HashMap<String, Sandbox.Student>();

for (Map.Entry<String, Student> entry : students_.entrySet()) {
    // If the entry key is "John*", this code will match if name = "John Smith"
    if (name.matches("^.*" + entry.getKey().replace("*", ".*") + ".*$")) {
        // do something with the matching map entry
        System.out.println("Student " + entry.getValue() + " matched " + entry.getKey());
    }
}

由於散列函數,使用hasmap無法實現。 它必須分配"John*"的散列和"John Smith"等的散列。 相同的價值。

您可以使用TreeMap創建它,如果您編寫自己的自定義類WildcardString包裝String,並以"John*".compareTo("John Smith")返回0的方式實現compareTo "John*".compareTo("John Smith")您可以使用正則表達式來執行此操作其他答案已經指出。

看到你想要widlcard匹配列表,你可以隨時刪除條目,並迭代TreeMap.get() 記得在完成名稱后將鑰匙放回去。

這只是實現它的一種可能方式。 使用少於200個元素,你可以很好地迭代。

更新:要在TreeSet上正確強加順序,您可以區分比較兩個WildcardString (意味着它是鍵之間的比較)和將WildcardStringString (將鍵與搜索值進行比較)進行比較的情況。

您可以迭代Map而不將其轉換為列表,並使用String matches函數,wih使用正則表達式。

如果你想避免循環,可以像這樣使用番石榴

@Test
public void hashsetContainsWithWildcards() throws Exception {
Set<String> students = new HashSet<String>();
students.add("John*");
students.add("Jo*Smith");
students.add("Bill");

Set<String> filteredStudents = Sets.filter(students, new Predicate<String>() {
  public boolean apply(String string) {
    return "JohnSmith".matches(string.replace("*", ".*"));
  }
});

assertEquals(2, filteredStudents.size());
assertTrue(filteredStudents.contains("John*"));
assertTrue(filteredStudents.contains("Jo*Smith"));

}

暫無
暫無

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

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