Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find a key in a map based on a pattern matching in java?

Tags:

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?

like image 456
нαƒєєz Avatar asked Apr 08 '15 19:04

нαƒєєz


People also ask

How does Java find the values with a given key in a map?

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.


1 Answers

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()); 
like image 174
Alexis C. Avatar answered Sep 28 '22 07:09

Alexis C.