Find a specific key out of few given keys from a hashmap in Java 8

Viewed 55

I have the following hashmap out of which I want to find if it contains a specific key out of the below 4 keys. In Java 7 I can do below. How can I do the same in Java8?

Map<String, String> filterParamsMap = new HashMap<>();
filterParamsMap.put("CRN", "1234");

String key;
for (String customReference : filterParamsMap.keySet()) {
    if (customReference.equalsIgnoreCase("CCN") || customReference.equalsIgnoreCase("PRN")
    || customReference.equalsIgnoreCase("PCCN") || customReference.equalsIgnoreCase("CRN")) {

                key = customReference;
    }

I tried but I'm able to check just 1 string out of the above 4. Also, it returns boolean whereas my output should be a String.

String key = filterParamsMap.keySet().stream().anyMatch(r->r.contains("CRN"));

I cannot do the below:

String key = filterParamsMap.keySet().stream().anyMatch(r->r.contains("CRN")||r->r.contains("PRN")||r->r.contains("PCCN")
                ||r->r.contains("CCN"));
2 Answers

You should be able to use anyMatch() along with String#matches():

String regex = "CRN|PRN|PCCN|CCN"
List<String> matchedResults = filterParamsMap.keySet().stream().filter(key -> key.matches(regex)).map(filterParamsMap::get).collect(Collectors.toList());

Here are using a regex alternation which contains the 4 possible key values which you want to match. Note that String#matches() implicitly applies the input pattern to the entire string. More generally, we would use the following regex pattern:

^(?:CRN|PRN|PCCN|CCN)$

You can use filter function and then find the first occurence.

String key = filterParamsMap.keySet()
            .stream()
            .filter(r -> {return r.contains("CRN") || r.contains("PRN") || r.contains("PCCN") || r.contains("CCN");})
            .findFirst().orElse(null);

findFirst() returns Optional you can use this object later on to validate further. In my example above I return null object if no object found because get() method will throw NoSuchElementException if there is no object found, but the behavior is up to you maybe you want to catch this exception or not this is for example purposes only.

Related