CookieMonster
CookieMonster

Reputation: 846

Java HashMap key fits to a pattern?

I have a Map dataset, and I want to iterate through the keys and search for matches. So I want to find the maps element, where the key fits to this pattern:

    String searchedKey = "A?C"; // ? means it can be any character
    
    Map<String, MyObject> myMap = new HashMap<>();
    myMap.put("ABC", MyObject(1));
    myMap.put("CDF", MyObject(2));
    myMap.put("ADS", MyObject(3));
    
    for (Map.Entry<String,MyObject> entry : myMap.entrySet()) {
        // in this case, I want to find the first element, because it's key fits the searchedKey, where ? can be anything
    }

How can I do this? Thanks!

Upvotes: 0

Views: 187

Answers (2)

Basti
Basti

Reputation: 1190

You could use Regex-Patterns that allow to search Strings for matchings of a logical sequence using String#matches(String).

Here is a page that might help you create and test a regex for your needs. You might also have to construct your pattern flexible during runtime, depending on how your search works.

Tho keep in mind that a HashMap does not keep the order in which the keys were inserted. keySet() does not return them in a fixed order. If you need them ordered, you could use a LinkedHashMap

Upvotes: 0

WJS
WJS

Reputation: 40024

You could do something like this to return a list of found MyObjects. Note I changed ? to . for any character.

String searchedKey = "A.C"; // ? means it can be any character

Map<String, MyObject> myMap = new HashMap<>();
myMap.put("ABC", new MyObject(1));
myMap.put("CDF", new MyObject(2));
myMap.put("ARS", new MyObject(3));
myMap.put("VS", new MyObject(4));
myMap.put("AQC", new MyObject(3));
myMap.put("DS", new MyObject(3));
myMap.put("ASC", new MyObject(10));

List<Map.Entry<String,MyObject>> list = myMap.entrySet().stream()
        .filter(e -> e.getKey().matches(searchedKey))
        .collect(Collectors.toList());


list.forEach(System.out::println);
    

Prints

ASC=10
ABC=1
AQC=3

The MyObject class


class MyObject {
    int val;
    
    public MyObject(int v) {
        this.val = v;
    }
    
    public String toString() {
        return val + "";
    }
}

Upvotes: 2

Related Questions