I want to find keys in a map with a pattern matching.
Ex:- Map<String, String> map = new HashMap<String, String>(); map.put("address1", "test test test"); map.put("address2", "aaaaaaaaaaa"); map.put("fullname", "bla bla");
From above map, I want to get the values of keys which has prefix of "address". So as in this example output should be the first two results ("address1" and "address2").
How can I achieve this dynamically?
HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
You can grab the keySet
of the map and then filter to get only keys that starts with "address" and add the valid keys to a new Set.
With Java 8, it's a bit less verbose:
Set<String> set = map.keySet() .stream() .filter(s -> s.startsWith("address")) .collect(Collectors.toSet());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With