Skip to content
Advertisement

java 8 Optional with Map<String, Set> [closed]

I have a Map<String, Set> getProperties which returns {BUILDING=[a, b, c]}, {NEW_BUILDING=[a, b, c, d, e]}, {OLD_BUILDING=[d, e]}..

I want to switch between BUILDING, NEW_BUILDING and OLD_BUILDING based on the value.

I am trying something like

return Optional.ofNullable(properties.get("BUILDING")).map(a -> {
            if(a.contains(code)) {
                return callMethod;
            } else {
                return null;
            }
        }).get();

I want to return based on BUILDING, NEW_BUILDING and OLD_BUIDLING

Advertisement

Answer

Try the below code:

Set<Map.Entry<String, Set<String>>> entries = properties.entrySet();
        for (Map.Entry<String, Set<String>> entry : entries) {
            Set<String> value = entry.getValue();
            if (value.contains(code)) {
                switch (entry.getKey()) {
                    case "BUILDING":
                        return callBuidingMethod;
                    case "OLD_BUILDING":
                        return callNewBuilding;
                    case "NEW_BUILDING":
                        return callOldBuilding;
                    default:
                        return null;
                }
            }
        }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement