Get a list of keys in a HashMap that have a key of type "some value",

In Mysql, we can query the table with the sentence “ WHERE is the name LIKE '% someName%' ”, can we have the same functions with the HashMap in java, if so, how can we achieve this more efficiently in less time, is not repeated for each element ?

+4
source share
4 answers

You can iterate over all of your keys and check if they match the regular expression. This may not be the most effective way to do this, but this is the first thing I thought about. Here's what it looks like:

Pattern p = Pattern.compile("*someName*"); // the regexp you want to match

List<String> matchingKeys = new ArrayList<>();
for (String key : map.keySet()) {
    if(p.matcher(key).matches()) {
        matchingKeys.add(key);
    }
}

// matchingKeys now contains the keys that match the regexp

: map :

HashMap<String, SomeValueClass> map = new HashMap<>();
+2

Java SE 8 API Streams: filter, , , .

. - (!):

myMap.entrySet().stream().filter(entry -> entry.getKey().contains("someName")).map(entry -> entry.getValue()).collect(Collectors.toList());
+3

Java , HashMap .

+1

, , .

/ , . - :

List<KeyType> keys = new ArrayList<>();
for (Map.Entry<KeyType, ValueType> e : myMap)
    if(e.getValue().equals(valueWeAreSearchingFor)) keys.add(e.getKey());
0

Source: https://habr.com/ru/post/1536919/


All Articles