Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

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

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:com.zxy.commons.json.JsonTest.java

@Test
public void map() {
    Map<String, Long> map = new LinkedHashMap<>();
    map.put("0", 11L);
    map.put("1-10", 22L);
    map.put("11-30", 20L);
    map.put("31-100", 25L);
    map.put("100", 15L);

    String mapString = JsonUtils.toJson(map);
    System.out.println("mapString:" + mapString);

    Map<String, Long> maps = JsonUtils.toMap(mapString, String.class, Long.class);
    //        for(Map.Entry<String, Long> value : maps.entrySet()) {
    //            System.out.println("key: "+value.getKey()+", value: "+value.getValue());
    //        }//from w w  w  . j  a  va 2 s  .  com
    maps.forEach((key, value) -> {
        System.out.println("key: " + key + ", value: " + value);
    });
    Assert.assertNotNull(maps);
}

From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.ProviderInterface.java

public void reapOrcaServerGroups(AccountDeploymentDetails<T> details, OrcaService orcaService) {
    Orca orca = connectTo(details, orcaService);
    Map<String, Orca.ActiveExecutions> executions = orca.getActiveExecutions();

    Map<String, Integer> executionsByServerGroup = new HashMap<>();

    // Record the total number of executions in each pool of orcas.
    executions.forEach((s, e) -> {
        String instanceName = s.split("@")[1];
        String serverGroupName = getServerGroupFromInstanceId(details, orcaService, instanceName);
        int count = executionsByServerGroup.getOrDefault(serverGroupName, 0);
        count += e.getCount();//w  ww .j  a va  2  s .  c o  m
        executionsByServerGroup.put(serverGroupName, count);
    });

    // Omit the last deployed orcas from being deleted, since they are kept around for rollbacks.
    List<String> allOrcas = new ArrayList<>(executionsByServerGroup.keySet());
    allOrcas.sort(String::compareTo);

    int orcaCount = allOrcas.size();
    if (orcaCount <= MAX_REMAINING_SERVER_GROUPS) {
        return;
    }

    allOrcas = allOrcas.subList(0, orcaCount - MAX_REMAINING_SERVER_GROUPS);
    for (String orcaName : allOrcas) {
        // TODO(lwander) consult clouddriver to ensure this orca isn't enabled
        if (executionsByServerGroup.get(orcaName) == 0) {
            DaemonTaskHandler.log("Reaping old orca instance " + orcaName);
            deleteServerGroup(details, orcaService, orcaName);
        }
    }
}

From source file:org.onosproject.imr.rest.ImrWebResource.java

/**
 * Build the JSON Node from the monitored intents retrieved from {@link IntentMonitorAndRerouteService}.
 *
 * @param monIntents Monitored intents structure.
 * @return {@link ArrayNode} built from the monitored intents.
 *///from www .j a v  a 2 s.  c  o  m
private ArrayNode getJsonMonitoredIntents(
        Map<ApplicationId, Map<Key, Pair<Set<ElementId>, Set<ElementId>>>> monIntents) {
    final ArrayNode rootArrayNode = mapper.createArrayNode();
    monIntents.forEach((appId, mapIntentKeyEndElements) -> {
        ObjectNode appObjNode = codec(ApplicationId.class).encode(appId, this);
        ArrayNode intentArrayNode = appObjNode.putArray("intents");
        mapIntentKeyEndElements.forEach((intentKey, inOutElem) -> {
            ObjectNode intentKeyObjNode = mapper.createObjectNode().put("key", intentKey.toString());
            ArrayNode inElements = intentKeyObjNode.putArray("inElements");
            inOutElem.getLeft().forEach(elementId -> inElements.add(elementId.toString()));
            ArrayNode outElements = intentKeyObjNode.putArray("outElements");
            inOutElem.getRight().forEach(elementId -> outElements.add(elementId.toString()));
            intentArrayNode.add(intentKeyObjNode);
        });

        rootArrayNode.add(appObjNode);
    });
    return rootArrayNode;
}

From source file:org.hsweb.web.service.impl.form.validator.java.JavaDycBeanValidator.java

public boolean validateMap(Map<Object, Object> data, Operation operation) {
    ValidateResults results = new ValidateResults();
    try {//  w  w w.  java  2 s.  co  m
        Object validatorTarget = clazz.newInstance();
        Set<ConstraintViolation<Object>> result = new LinkedHashSet<>();
        if (operation == Operation.INSERT) {
            data.forEach((key, value) -> {
                try {
                    BeanUtils.setProperty(validatorTarget, (String) key, value);
                } catch (Exception e) {
                }
            });
            result.addAll(hibernateValidator.validate(validatorTarget));
        } else
            data.forEach((key, value) -> {
                Field field = ReflectionUtils.findField(clazz, (String) key);
                if (field != null)
                    result.addAll(hibernateValidator.validateValue(clazz, (String) key, value));
            });
        if (result.size() > 0) {
            for (ConstraintViolation<Object> violation : result) {
                String property = violation.getPropertyPath().toString();
                results.addResult(property, violation.getMessage());
            }
        }
    } catch (Exception e) {
        throw new BusinessException("??", e, 500);
    }
    if (results.size() > 0)
        throw new ValidationException(results.get(0).getMessage(), results);
    return true;
}

From source file:com.github.blindpirate.gogradle.task.go.GoTest.java

private Map<File, List<File>> determineTestPattern() {
    if (isEmpty(testNamePattern)) {
        // https://golang.org/cmd/go/#hdr-Description_of_package_lists
        Collection<File> allTestFiles = filterGoFiles(getProjectDir(), PROJECT_TEST_FILES_ONLY);
        return groupByParentDir(allTestFiles);
    } else {/*from  w  ww . j a  v  a  2 s  .c om*/
        Collection<File> filesMatchingPatterns = filterTestsMatchingPattern(getProjectDir(), testNamePattern);

        if (filesMatchingPatterns.isEmpty()) {
            LOGGER.quiet("No tests matching " + testNamePattern.stream().collect(joining("/")) + ", skip.");
            return Collections.emptyMap();
        } else {
            LOGGER.quiet("Found " + filesMatchingPatterns.size() + " files to test.");

            Map<File, List<File>> parentDirToFiles = groupByParentDir(filesMatchingPatterns);

            parentDirToFiles.forEach((parentDir, tests) -> tests.addAll(getAllNonTestGoFiles(parentDir)));

            return parentDirToFiles;
        }
    }
}

From source file:com.streamsets.pipeline.stage.processor.tensorflow.TensorFlowProcessor.java

private Map<Pair<String, Integer>, Tensor> createInputTensor(Map<Pair<String, Integer>, Buffer> inputBuffer,
        int numberOfRecords) {
    Map<Pair<String, Integer>, Tensor> inputs = new LinkedHashMap<>();
    inputBuffer.forEach((k, v) -> {
        TensorInputConfig inputConfig = inputConfigMap.get(k);
        TensorDataTypeSupport dtSupport = TensorTypeSupporter.INSTANCE
                .getTensorDataTypeSupport(inputConfig.tensorDataType);
        long[] inputSize = (conf.useEntireBatch) ? new long[] { 1, numberOfRecords, inputConfig.fields.size() }
                : new long[] { numberOfRecords, inputConfig.fields.size() };
        //for read
        v.flip();/*  ww w  .j a v  a  2  s  .c o  m*/
        inputs.put(k, dtSupport.createTensor(inputSize, v));
    });
    return inputs;
}

From source file:cc.redpen.server.api.RedPenService.java

/**
 * Create a new redpen for the specified language. The validator properties map is a map of validator names to their (optional) properties.
 * Only validitors present in this map are added to the redpen configuration
 *
 * @param lang                the language to use
 * @param validatorProperties a map of redpen validator names to a map of their properties
 * @return a configured redpen instance/*from  w  w  w.jav a 2 s  . c  om*/
 */
public RedPen getRedPen(String lang, Map<String, Map<String, String>> validatorProperties) {
    Configuration.ConfigurationBuilder configBuilder = Configuration.builder(lang).secure();

    // add the validators and their properties
    validatorProperties.forEach((validatorName, props) -> {
        ValidatorConfiguration validatorConfig = new ValidatorConfiguration(validatorName);
        props.forEach(validatorConfig::addProperty);
        configBuilder.addValidatorConfig(validatorConfig);
    });
    try {
        return new RedPen(configBuilder.build());
    } catch (RedPenException e) {
        LOG.error("Unable to initialize RedPen", e);
        throw new ExceptionInInitializerError(e);
    }
}

From source file:org.springframework.cloud.gateway.handler.FilteringWebHandler.java

public FilteringWebHandler(WebHandler targetHandler, GatewayProperties gatewayProperties,
        List<GlobalFilter> globalFilters, Map<String, RouteFilter> routeFilters) {
    super(targetHandler);
    this.gatewayProperties = gatewayProperties;
    this.globalFilters = initList(globalFilters);
    routeFilters.forEach((name, def) -> this.routeFilters.put(normalizeName(name), def));
}

From source file:org.wso2.carbon.identity.application.authentication.framework.handler.claims.impl.DefaultClaimFilter.java

private List<ClaimMapping> getSpClaimMappings(ApplicationConfig appConfig) {

    Map<String, String> spClaimMapping = appConfig.getClaimMappings();
    Map<String, String> mandatoryClaims = appConfig.getMandatoryClaimMappings();
    Map<String, String> requestedClaims = appConfig.getRequestedClaimMappings();

    List<ClaimMapping> spClaimMappingsList = new ArrayList<>();
    spClaimMapping.forEach((key, value) -> {
        ClaimMapping claimMapping = ClaimMapping.build(value, key, null, false);
        mandatoryClaims.entrySet().stream().filter(entry1 -> key.equals(entry1.getKey())).map(entry1 -> true)
                .forEach(claimMapping::setMandatory);
        requestedClaims.entrySet().stream().filter(entry2 -> key.equals(entry2.getKey())).map(entry2 -> true)
                .forEach(claimMapping::setRequested);
        spClaimMappingsList.add(claimMapping);
    });//from  ww w .  ja va 2  s . co  m
    return spClaimMappingsList;
}

From source file:org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig.java

/**
 * Sets the adjacency SIDs of the router.
 *
 * @param adjacencySids adjacency SIDs of the router.
 * @return the config of the router.// w w w. java2 s . com
 */
public SegmentRoutingDeviceConfig setAdjacencySids(Map<Integer, Set<Integer>> adjacencySids) {
    if (adjacencySids == null) {
        object.remove(ADJSIDS);
    } else {
        ArrayNode adjacencySidsNode = mapper.createArrayNode();

        adjacencySids.forEach((sid, ports) -> {
            ObjectNode adjacencySidNode = mapper.createObjectNode();

            adjacencySidNode.put(ADJSID, sid);

            ArrayNode portsNode = mapper.createArrayNode();
            ports.forEach(port -> {
                portsNode.add(port.toString());
            });
            adjacencySidNode.set(PORTS, portsNode);

            adjacencySidsNode.add(adjacencySidNode);
        });

        object.set(ADJSIDS, adjacencySidsNode);
    }

    return this;
}