Example usage for java.util Map computeIfPresent

List of usage examples for java.util Map computeIfPresent

Introduction

In this page you can find the example usage for java.util Map computeIfPresent.

Prototype

default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) 

Source Link

Document

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

Usage

From source file:Main.java

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();

    for (int i = 0; i < 10; i++) {
        map.putIfAbsent(i, "val" + i);
    }// w ww  .  ja v a2 s.  co  m

    map.forEach((id, val) -> System.out.println(val));

    map.computeIfPresent(3, (num, val) -> val + num);
    System.out.println(map.get(3)); // val33

    map.computeIfPresent(9, (num, val) -> null);
    System.out.println(map.containsKey(9)); // false

    map.computeIfAbsent(23, num -> "val" + num);
    System.out.println(map.containsKey(23)); // true

    map.computeIfAbsent(3, num -> "bam");
    System.out.println(map.get(3)); // val33
}

From source file:Main.java

public static void main(String[] args) {
    Map<String, Integer> wordCounts = new LinkedHashMap<String, Integer>();

    String s = "Lorem ipsum dolor sit amet consetetur iam nonumy sadipscing "
            + "elitr, sed diam nonumy eirmod tempor invidunt ut erat sed "
            + "labore et dolore magna dolor sit amet aliquyam erat sed diam";

    wordCounts.put("sed", 0);
    wordCounts.put("erat", 0);

    for (String t : s.split(" ")) {
        wordCounts.computeIfPresent(t, (k, v) -> v + 1);
    }//from   w  w w . ja va 2  s  .  c  om
    System.out.println(wordCounts);
}

From source file:io.coala.enterprise.Fact.java

/**
 * override and deserialize bean properties as declared in factType
 * <p>//from  w ww  . j  a  va  2  s .co  m
 * TODO detect properties from builder methods: {@code withKey(T value)}
 * 
 * @param om
 * @param json
 * @param factType
 * @param properties
 * @return the properties again, to allow chaining
 * @throws IntrospectionException
 */
static <T extends Fact> Map<String, Object> fromJSON(final ObjectMapper om, final TreeNode json,
        final Class<T> factType, final Map<String, Object> properties) {
    try {
        final ObjectNode tree = (ObjectNode) json;
        final BeanInfo beanInfo = Introspector.getBeanInfo(factType);
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors())
            if (tree.has(pd.getName()))
                properties.computeIfPresent(pd.getName(),
                        (property, current) -> JsonUtil.valueOf(om, tree.get(property), pd.getPropertyType()));
        return properties;
    } catch (final Throwable e) {
        return Thrower.rethrowUnchecked(e);
    }
}

From source file:org.openlmis.fulfillment.web.util.StockEventBuilder.java

private void convertQuantityToDispensingUnits(StockEventLineItemDto dto, Map<UUID, OrderableDto> orderables) {
    orderables.computeIfPresent(dto.getOrderableId(), (id, orderable) -> {
        Long netContent = orderables.get(dto.getOrderableId()).getNetContent();
        dto.setQuantity((int) (dto.getQuantity() * netContent));
        return orderable;
    });/*from  ww  w. jav a 2s. com*/
}

From source file:com.vmware.photon.controller.deployer.dcp.task.CreateIsoTaskService.java

private void applyMustacheParameters(String mustacheDirectory, ContainerService.State containerService,
        String containerType, FutureCallback<ContainerService.State> callback) {
    ServiceConfigurator serviceConfigurator = HostUtils.getServiceConfiguratorFactory(this).create();

    try {/*from w w  w .  j a va2s  .  co m*/
        Map<String, Object> dynamicParameters = new HashMap<>();
        if (containerService.dynamicParameters != null) {
            dynamicParameters.putAll(containerService.dynamicParameters);
        }

        // Deserialize the string to get load balancer servers and zookeeper quorum
        Type lbType = new TypeToken<ArrayList<LoadBalancerServer>>() {
        }.getType();
        dynamicParameters.computeIfPresent(BuildRuntimeConfigurationTaskService.ENV_LOADBALANCER_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), lbType));
        Type zkType = new TypeToken<ArrayList<ZookeeperServer>>() {
        }.getType();
        dynamicParameters.computeIfPresent(BuildRuntimeConfigurationTaskService.ENV_ZOOKEEPER_QUORUM,
                (k, v) -> new Gson().fromJson(v.toString(), zkType));

        serviceConfigurator.applyDynamicParameters(mustacheDirectory,
                ContainersConfig.ContainerType.valueOf(containerType), dynamicParameters);
        callback.onSuccess(containerService);
    } catch (Throwable t) {
        callback.onFailure(t);
    }
}

From source file:com.vmware.photon.controller.deployer.xenon.task.CreateDhcpVmTaskService.java

private void processContainerConfig(State currentState, Map<String, ContainerService.State> containerStates,
        Map<String, ContainerTemplateService.State> templateStates) throws Throwable {

    Path serviceConfigDirectoryPath = Files.createTempDirectory("mustache-" + currentState.vmId)
            .toAbsolutePath();/*www. ja v a2  s .  com*/
    ServiceUtils.logInfo(this, "Created service config directory: " + serviceConfigDirectoryPath.toString());
    ServiceConfigurator serviceConfigurator = HostUtils.getServiceConfiguratorFactory(this).create();
    serviceConfigurator.copyDirectory(HostUtils.getDeployerContext(this).getConfigDirectory(),
            serviceConfigDirectoryPath.toString());

    for (ContainerService.State containerState : containerStates.values()) {
        Map<String, Object> dynamicParameters = new HashMap<>();
        if (containerState.dynamicParameters != null) {
            dynamicParameters.putAll(containerState.dynamicParameters);
        }

        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_API_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTPS_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_COMMON_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_PHOTON_CONTROLLER_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_DEPLOYER_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));

        serviceConfigurator.applyDynamicParameters(serviceConfigDirectoryPath.toString(),
                ContainersConfig.ContainerType
                        .valueOf(templateStates.get(containerState.documentSelfLink).name),
                dynamicParameters);
    }

    State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null);
    patchState.serviceConfigDirectory = serviceConfigDirectoryPath.toString();
    TaskUtils.sendSelfPatch(this, patchState);
}

From source file:com.vmware.photon.controller.deployer.xenon.task.CreateManagementVmTaskService.java

private void processContainerConfig(State currentState, Map<String, ContainerService.State> containerStates,
        Map<String, ContainerTemplateService.State> templateStates) throws Throwable {

    Path serviceConfigDirectoryPath = Files.createTempDirectory("mustache-" + currentState.vmId)
            .toAbsolutePath();/*from w ww  .j  a  v  a 2  s.  co  m*/
    ServiceUtils.logInfo(this, "Created service config directory: " + serviceConfigDirectoryPath.toString());
    ServiceConfigurator serviceConfigurator = HostUtils.getServiceConfiguratorFactory(this).create();
    serviceConfigurator.copyDirectory(HostUtils.getDeployerContext(this).getConfigDirectory(),
            serviceConfigDirectoryPath.toString());

    for (ContainerService.State containerState : containerStates.values()) {
        Map<String, Object> dynamicParameters = new HashMap<>();
        if (containerState.dynamicParameters != null) {
            dynamicParameters.putAll(containerState.dynamicParameters);
        }

        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_API_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTPS_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_COMMON_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_PHOTON_CONTROLLER_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_DEPLOYER_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));

        // Convert the String values in the dynamic parameters to boolean values. This is needed for mustache to
        // correctly recognize the boolean values. For example, if "false" evaluates to true in mustache where "false"
        // is of type String. But, if false does not, where false is of type boolean.
        for (String key : dynamicParameters.keySet()) {
            if (dynamicParameters.get(key).equals("true")) {
                dynamicParameters.put(key, true);
            }
            if (dynamicParameters.get(key).equals("false")) {
                dynamicParameters.put(key, false);
            }
        }

        serviceConfigurator.applyDynamicParameters(serviceConfigDirectoryPath.toString(),
                ContainersConfig.ContainerType
                        .valueOf(templateStates.get(containerState.documentSelfLink).name),
                dynamicParameters);
    }

    State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null);
    patchState.serviceConfigDirectory = serviceConfigDirectoryPath.toString();
    TaskUtils.sendSelfPatch(this, patchState);
}

From source file:com.vmware.photon.controller.deployer.dcp.task.CreateManagementVmTaskService.java

private void processContainerConfig(State currentState, Map<String, ContainerService.State> containerStates,
        Map<String, ContainerTemplateService.State> templateStates) throws Throwable {

    Path serviceConfigDirectoryPath = Files.createTempDirectory("mustache-" + currentState.vmId)
            .toAbsolutePath();/* w w w.j a v a  2  s  .  c om*/
    ServiceUtils.logInfo(this, "Created service config directory: " + serviceConfigDirectoryPath.toString());
    ServiceConfigurator serviceConfigurator = HostUtils.getServiceConfiguratorFactory(this).create();
    serviceConfigurator.copyDirectory(HostUtils.getDeployerContext(this).getConfigDirectory(),
            serviceConfigDirectoryPath.toString());

    for (ContainerService.State containerState : containerStates.values()) {
        Map<String, Object> dynamicParameters = new HashMap<>();
        if (containerState.dynamicParameters != null) {
            dynamicParameters.putAll(containerState.dynamicParameters);
        }

        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_API_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTP_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_HAPROXY_MGMT_UI_HTTPS_SERVERS,
                (k, v) -> new Gson().fromJson(v.toString(), loadBalancerTypeToken.getType()));
        dynamicParameters.computeIfPresent(BuildRuntimeConfigurationTaskService.MUSTACHE_KEY_COMMON_PEER_NODES,
                (k, v) -> new Gson().fromJson(v.toString(), peerNodeTypeToken.getType()));
        dynamicParameters.computeIfPresent(
                BuildContainersConfigurationWorkflowService.MUSTACHE_KEY_ZOOKEEPER_INSTANCES,
                (k, v) -> new Gson().fromJson(v.toString(), zookeeperTypeToken.getType()));

        serviceConfigurator.applyDynamicParameters(serviceConfigDirectoryPath.toString(),
                ContainersConfig.ContainerType
                        .valueOf(templateStates.get(containerState.documentSelfLink).name),
                dynamicParameters);
    }

    State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null);
    patchState.serviceConfigDirectory = serviceConfigDirectoryPath.toString();
    TaskUtils.sendSelfPatch(this, patchState);
}