问题
I'm new to Hazelcast - evaluating and prototyping to see if it fits our distributed memory cache needs. One of the requirements was to be able to use wild cards to search for keys in a given map. Looking through the IMap documentation, looks like keySet(Predicate predicate) can be used. But I couldn't figure how to use the Predicate in such a way that given a wild card string, a keySet is returned containing all keys that match. An example will be helpful.
A snippet of my code. This is the client side.
IMap<String, String> mapTest1 = client.getMap("testMap");
mapTest1.put( "testKey1", "This is a Test" );
mapTest1.put( "testKey2", "This value has a long key name" );
mapTest1.put( "key3", "Another value" );
// Need a wild card search on the map, such that all keys with "%test%" will be returned.
Thanks.
回答1:
This should do the trick if I understood your request correctly:
public class Test {
public static void main(String[] args) {
HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
IMap<String, String> map = hazelcastInstance.getMap("someMap");
Collection<String> keys = map.keySet(
new RegexPredicate("[a-z].*[a-z0-9]"));
System.out.println(keys);
}
public static class RegexPredicate implements Predicate<String, String> {
private String regex;
private transient Pattern pattern;
public RegexPredicate(String regex) {
this.regex = regex;
}
@Override
public boolean apply(Map.Entry<String, String> mapEntry) {
if (pattern == null) {
pattern = Pattern.compile(regex);
}
Matcher matcher = pattern.matcher(mapEntry.getKey());
return matcher.matches();
}
}
}
来源:https://stackoverflow.com/questions/28591381/using-predicate-to-search-a-keyset-in-hazelcast