Example usage for java.util HashMap forEach

List of usage examples for java.util HashMap forEach

Introduction

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

Prototype

@Override
    public void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Usage

From source file:org.pentaho.js.require.RebuildCacheCallable.java

private static void makePathsAbsolute(Map<String, Object> result, String baseUrl) {
    HashMap<String, String> paths = (HashMap<String, String>) result.get("paths");
    paths.forEach((moduleId, location) -> {
        if (checkNeedsBaseUrl(location)) {
            paths.put(moduleId, baseUrl + location);
        }//  w ww  . j  av  a2  s  .  com
    });

    ArrayList<Object> packages = (ArrayList<Object>) result.get("packages");
    final ArrayList<Object> convertedPackages = packages.stream().filter(Objects::nonNull)
            .map(packageDefinition -> {
                if (packageDefinition instanceof HashMap) {
                    final HashMap<String, String> complexPackageDefinition = (HashMap<String, String>) packageDefinition;

                    if (complexPackageDefinition.containsKey("location")) {
                        String location = complexPackageDefinition.get("location");
                        if (checkNeedsBaseUrl(location)) {
                            complexPackageDefinition.put("location", baseUrl + location);
                            return complexPackageDefinition;
                        }
                    }
                }

                return packageDefinition;
            }).collect(Collectors.toCollection(ArrayList<Object>::new));

    result.put("packages", convertedPackages);
}

From source file:com.glluch.ecf2xmlmaven.Writer.java

protected static void writeHM2solr(HashMap<String, String> map, String path, String solrType, String code,
        String solrComment) {/*from  ww  w.java2  s .  c o  m*/
    map.forEach((String key, String value) -> {

        try {
            writePart2Solr(path, value, solrType, code + key, solrComment);
        } catch (IOException ex) {
            Logger.getLogger(Writer.class.getName()).log(Level.SEVERE, null, ex);
        }

    });//end forEach
}

From source file:Main.java

/**
 * Returns a HashSet of values in a HashMap that match the specified Predicate.
 * @param map the HashMap to check against
 * @param condition the Predicate to check
 * @param <K> the type of the Key in the HashMap
 * @param <V> the type of the Value in the HashMap
 * @return a HashSet of values matching the predicate, empty HashSet if no results found
 * @throws IllegalArgumentException if HashMap or Predicate is null
 *//*w w w  .j a  v a 2s . c  o  m*/
public static <K, V> HashSet<V> getValuesInHashMap(final HashMap<K, V> map, final Predicate<V> condition) {
    final HashSet<V> matchingValues = new HashSet<>();

    if (map == null)
        throw new IllegalArgumentException("HashMap cannot be null!");
    if (condition == null)
        throw new IllegalArgumentException("Predicate cannot be null!");

    map.forEach((key, value) -> {
        if (condition.test(value))
            matchingValues.add(value);
    });

    return matchingValues;
}

From source file:com.scaniatv.LangFileUpdater.java

/**
 * Method that converts the lang map to a JSON array for the panel to us.
 * //from  ww  w. j  a  v a 2s  . c  o  m
 * @param map
 * @return 
 */
private static String convertLangMapToJSONArray(HashMap<String, String> map) {
    final JSONStringer jsonArray = new JSONStringer();

    // Make a new array.
    jsonArray.array();

    map.forEach((String key, String value) -> {
        final JSONObject obj = new JSONObject();

        jsonArray.object().key("id").value(key).key("response").value(value).endObject();
    });

    // Close the array.
    jsonArray.endArray();

    // This part is a bit slow.
    return jsonArray.toString();
}

From source file:org.briljantframework.data.Collectors.java

public static <T> Collector<T, ?, Vector> valueCounts() {
    return Collector.of(HashMap::new, (map, t) -> map.compute(t, (v, c) -> c == null ? 1 : c + 1),
            new BinaryOperator<HashMap<T, Integer>>() {
                @Override/*from  ww  w.jav  a  2 s.  co m*/
                public HashMap<T, Integer> apply(HashMap<T, Integer> left, HashMap<T, Integer> right) {
                    right.forEach((k, v) -> left.merge(k, v, (Integer o, Integer n) -> o == null ? n : o + n));
                    return left;
                }
            }, (map) -> {
                Vector.Builder b = new TypeInferenceVectorBuilder();
                for (Map.Entry<T, Integer> e : map.entrySet()) {
                    b.set(e.getKey(), e.getValue());
                }
                return b.build();
            }, Collector.Characteristics.UNORDERED);
}

From source file:com.scaniatv.LangFileUpdater.java

/**
 * Method that gets the ID from the custom and default lang file, and adds 
 * missing lang IDs to the custom one, plus returns the lang ID and matches in a HashMap.
 * //from  w ww  .  jav  a2 s .  c o  m
 * @param defaultLang
 * @param customLang
 * @return 
 */
private static HashMap<String, String> getCustomAndDefaultLangMap(String defaultLang, String customLang) {
    // Create a new patter that will match if the default lang ID is also in the custom one.
    final Pattern pattern = Pattern.compile(
            "^\\$\\.lang\\.register\\((\\'|\\\")([a-zA-Z0-9,.-]+)(\\'|\\\")\\,\\s(\\'|\\\")(.*)(\\'|\\\")\\);",
            Pattern.MULTILINE);

    // Get all matches for the default lang.
    final Matcher m1 = pattern.matcher(defaultLang);
    final HashMap<String, String> defaultMatches = new HashMap<>();
    while (m1.find()) {
        defaultMatches.put(m1.group(2), m1.group(5));
    }

    // Get all matches for the custom lang.
    final Matcher m2 = pattern.matcher(customLang);
    final HashMap<String, String> customMatches = new HashMap<>();
    while (m2.find()) {
        customMatches.put(m2.group(2), m2.group(5));
    }

    // Check if any is missing in the custom one.
    defaultMatches.forEach((String key, String value) -> {
        if (!customMatches.containsKey(key)) {
            customMatches.put(key, value);
        }
    });

    return customMatches;
}

From source file:org.apache.eagle.alert.engine.evaluator.impl.SiddhiPolicyHandler.java

public void restoreSiddhiSnapshot(byte[] siddhiSnapshot) {
    HashMap<String, Object[]> snapshots = (HashMap<String, Object[]>) ByteSerializer.BToO(siddhiSnapshot);
    HashMap<String, Object[]> modifiedSnapshots = new HashMap<>(snapshots.size());
    snapshots.forEach((oldElementId, snapshot) -> {
        String[] splitedId = StringUtils.split(oldElementId, "-");
        String newElementId = executionRuntime.getName() + "-" + splitedId[splitedId.length - 1];
        modifiedSnapshots.put(newElementId, snapshot);
    });/* ww w .  j  a v  a2s . c  om*/
    siddhiSnapshot = ByteSerializer.OToB(modifiedSnapshots);
    LOG.info("Restoring SiddhiSnapshot Start");
    this.executionRuntime.restore(siddhiSnapshot);
    LOG.info("Restoring SiddhiSnapshot End");
}

From source file:com.viettel.util.doc.DocsUtility.java

public void replaceValues(HashMap<String, String> maps) {
    maps.forEach((t, u) -> {
        replacePlaceholder(u, t);
    });
}

From source file:org.thingsplode.synapse.serializers.jackson.JacksonSerializer.java

private void registerHandlers(List<JsonSerializer> serializers,
        HashMap<Class, JsonDeserializer> deSerializers) {

    if (serializers != null && !serializers.isEmpty()) {
        serializers.forEach(s -> module.addSerializer(s));
    }/*from  w  w  w.j a v  a  2s  .c  o m*/
    if (deSerializers != null && !deSerializers.isEmpty()) {
        deSerializers.forEach((k, v) -> module.addDeserializer(k, v));
    }

}

From source file:com.falcon.orca.actors.ClusterManager.java

@Override
public void onReceive(Object message) {

    if (message instanceof ClusterEvent.CurrentClusterState) {
        log.info("Got message of type Current cluster state");
    } else if (message instanceof ClusterEvent.MemberUp) {
        ClusterEvent.MemberUp memberUp = (ClusterEvent.MemberUp) message;
        //if(memberUp.member().hasRole("node_manager")) {
        NodeManagerCommand command = new NodeManagerCommand();
        command.setType(NodeManagerCommandType.REGISTER_TO_MASTER);
        getContext().actorSelection(memberUp.member().address() + "/user/node_manager").tell(command,
                getSelf());/*ww w.ja v a 2 s  .  c  o m*/
        //}
    } else if (message instanceof ClusterEvent.MemberExited) {
        nodeManagers.remove(getSender());
    } else if (message instanceof ClusterEvent.UnreachableMember) {
        log.info("Got message of type unreachable member " + getSender());
        nodeManagers.remove(getSender());
    } else if (message instanceof ClusterManagerCommand) {
        switch (((ClusterManagerCommand) message).getType()) {
        case REGISTER_NODE:
            nodeManagers.add(getSender());
            if (nodeManagers.size() >= minimumNodes) {
                printOnCmd("Minimum number of nodes in cluster complete, you can run tests now.");
            }
            break;
        case UNREGISTER_NODE: {
            printOnCmd("Got a node disconnect request, current size " + nodeManagers.size());
            nodeManagers.remove(getSender());
            printOnCmd("Removing node from cluster after removal size " + nodeManagers.size());
            break;
        }
        case START_LOAD: {
            try {
                if (nodeManagers.size() < minimumNodes) {
                    printOnCmd("Not enough numbers of nodes, have patience.");
                } else if (isBusy) {
                    printOnCmd("Already a run going on can't start another, wait for it to finish");
                } else {
                    isBusy = true;
                    busyNodes = 0;
                    pausedNodes = 0;
                    mergedResponseTimes.clear();
                    runResults.clear();
                    nodeManagers.forEach((o) -> {
                        NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                        nodeManagerCommand.setType(NodeManagerCommandType.CLEAR_LOAD_DATA);
                        o.tell(nodeManagerCommand, getSelf());
                    });
                    ClusterManagerCommand managerCommand = (ClusterManagerCommand) message;
                    RunDetails runDetails = (RunDetails) managerCommand.getFromContext("runDetails");
                    if (runDetails.isUrlDynamic() || runDetails.isBodyDynamic()) {
                        DataReader dataReader = new JsonFileReader(runDetails.getDataFilePath(),
                                runDetails.getTemplateFilePath());
                        HashMap<String, HashMap<String, List<Object>>> dynDataFromFile = dataReader
                                .readVariableValues();
                        HashMap<String, HashMap<String, DynVarUseType>> dynVarUseTypeFromFile = dataReader
                                .readVariableUseType();
                        HashMap<String, DynGenerator> generators = dataReader.readGenerators();
                        if (generators != null) {
                            generators.forEach((k, v) -> nodeManagers.forEach((o) -> {
                                NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                                nodeManagerCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                nodeManagerCommand.putOnContext("key", k);
                                nodeManagerCommand.putOnContext("data", v);
                                nodeManagerCommand.putOnContext("dataType", "generator");
                                o.tell(nodeManagerCommand, getSelf());
                            }));
                        }
                        final int[] nodeManagerIndex = { 0 };
                        if (runDetails.isBodyDynamic()) {
                            HashMap<String, List<Object>> bodyParams = dynDataFromFile.get("bodyData");
                            HashMap<String, DynVarUseType> bodyParamsUseType = dynVarUseTypeFromFile
                                    .get("bodyVarUseType");
                            String template = dataReader.readTemplate();
                            if (!StringUtils.isBlank(template)) {
                                NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                                nodeManagerCommand.putOnContext("template", template);
                                nodeManagerCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                nodeManagers.forEach((o) -> o.tell(nodeManagerCommand, getSelf()));
                            }
                            bodyParams.forEach((k, v) -> {
                                List<List<Object>> partitions = Lists.partition(v,
                                        v.size() / nodeManagers.size());
                                nodeManagerIndex[0] = 0;
                                nodeManagers.forEach((o) -> {
                                    List<Object> partition = partitions.get(nodeManagerIndex[0]++);
                                    if (partition.size() < 10000) {
                                        NodeManagerCommand nodeDataCommand = new NodeManagerCommand();
                                        nodeDataCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                        nodeDataCommand.putOnContext("key", k);
                                        nodeDataCommand.putOnContext("data", new ArrayList(partition));
                                        nodeDataCommand.putOnContext("dataType", "body");
                                        nodeDataCommand.putOnContext("dataUseType", bodyParamsUseType.get(k));
                                        o.tell(nodeDataCommand, getSelf());
                                    } else {
                                        List<List<Object>> nodePartitions = Lists.partition(partition, 10000);
                                        for (List<Object> nodePartition : nodePartitions) {
                                            NodeManagerCommand nodeDataCommand = new NodeManagerCommand();
                                            nodeDataCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                            nodeDataCommand.putOnContext("key", k);
                                            nodeDataCommand.putOnContext("data", new ArrayList(nodePartition));
                                            nodeDataCommand.putOnContext("dataType", "body");
                                            nodeDataCommand.putOnContext("dataUseType",
                                                    bodyParamsUseType.get(k));
                                            o.tell(nodeDataCommand, getSelf());
                                        }
                                    }
                                });
                            });
                        }
                        if (runDetails.isUrlDynamic()) {
                            HashMap<String, List<Object>> urlParams = dynDataFromFile.get("urlData");
                            HashMap<String, DynVarUseType> urlParamsUseType = dynVarUseTypeFromFile
                                    .get("urlVarUseType");
                            //Block to send urlTemplate to each node
                            {
                                NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                                nodeManagerCommand.putOnContext("urlTemplate", runDetails.getUrl());
                                nodeManagerCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                nodeManagers.forEach((o) -> o.tell(nodeManagerCommand, getSelf()));
                            }

                            urlParams.forEach((k, v) -> {
                                List<List<Object>> partitions = Lists.partition(v,
                                        v.size() / nodeManagers.size());
                                nodeManagerIndex[0] = 0;
                                nodeManagers.forEach((o) -> {
                                    List<Object> partition = partitions.get(nodeManagerIndex[0]++);
                                    if (partition.size() < 10000) {
                                        NodeManagerCommand nodeDataCommand = new NodeManagerCommand();
                                        nodeDataCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                        nodeDataCommand.putOnContext("key", k);
                                        nodeDataCommand.putOnContext("data", new ArrayList<>(partition));
                                        nodeDataCommand.putOnContext("dataType", "url");
                                        nodeDataCommand.putOnContext("dataUseType", urlParamsUseType.get(k));
                                        o.tell(nodeDataCommand, getSelf());
                                    } else {
                                        List<List<Object>> nodePartitions = Lists.partition(partition, 10000);
                                        for (List<Object> nodePartition : nodePartitions) {
                                            NodeManagerCommand nodeDataCommand = new NodeManagerCommand();
                                            nodeDataCommand.setType(NodeManagerCommandType.TAKE_LOAD_DATA);
                                            nodeDataCommand.putOnContext("key", k);
                                            nodeDataCommand.putOnContext("data",
                                                    new ArrayList<>(nodePartition));
                                            nodeDataCommand.putOnContext("dataType", "url");
                                            nodeDataCommand.putOnContext("dataUseType",
                                                    urlParamsUseType.get(k));
                                            o.tell(nodeDataCommand, getSelf());
                                        }
                                    }
                                });
                            });
                        }
                        nodeManagers.forEach((o) -> {
                            NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                            nodeManagerCommand.setType(NodeManagerCommandType.LOAD_DATA_COMPLETE);
                            o.tell(nodeManagerCommand, getSelf());
                        });
                    }
                    nodeManagers.forEach((o) -> {
                        NodeManagerCommand command = new NodeManagerCommand();
                        command.putOnContext("runDetails", runDetails);
                        command.setType(NodeManagerCommandType.START_LOAD);
                        o.tell(command, getSelf());
                    });
                }
            } catch (IOException ie) {
                printOnCmd("Datareader failed to read data from file, make sure template file, datafile pathe"
                        + " are correct.");
                log.error("Datareader failed to load", ie);
                busyNodes = 0;
                isBusy = false;
            }
            break;
        }
        case LOAD_GENERATION_START: {
            busyNodes++;
            break;
        }
        case LOAD_GENERATION_COMPLETE: {
            runResults.add((RunResult) ((ClusterManagerCommand) message).getFromContext("runResult"));
            NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
            nodeManagerCommand.setType(NodeManagerCommandType.SEND_DATA);
            getSender().tell(nodeManagerCommand, getSelf());
            break;
        }
        case TAKE_DATA: {
            mergedResponseTimes
                    .addAll((List<Long>) ((ClusterManagerCommand) message).getFromContext("responseTimes"));
            break;
        }
        case DATA_SEND_COMPLETE: {
            busyNodes--;
            if (busyNodes <= 0) {
                isBusy = false;
                printMergedResult(runResults, mergedResponseTimes);
            }
            break;
        }
        case STOP_LOAD: {
            nodeManagers.forEach((o) -> {
                NodeManagerCommand command = new NodeManagerCommand();
                command.setType(NodeManagerCommandType.STOP_LOAD);
                o.tell(command, getSelf());
            });
            break;
        }
        case PAUSE_LOAD: {
            nodeManagers.forEach((o) -> {
                NodeManagerCommand command = new NodeManagerCommand();
                command.setType(NodeManagerCommandType.PAUSE_LOAD);
                o.tell(command, getSelf());
            });
            break;
        }
        case LOAD_GENERATION_PAUSED: {
            pausedNodes++;
            if (Objects.equals(pausedNodes, busyNodes)) {
                isPaused = true;
            }
            break;
        }
        case LOAD_GENERATION_RESUMED: {
            pausedNodes--;
            if (pausedNodes <= 0) {
                isPaused = false;
            }
            break;
        }
        case RESUME_LOAD: {
            nodeManagers.forEach((o) -> {
                NodeManagerCommand command = new NodeManagerCommand();
                command.setType(NodeManagerCommandType.RESUME_LOAD);
                o.tell(command, getSelf());
            });
            break;
        }
        case CLUSTER_DETAILS:
            printOnCmd(printClusterDetails(isBusy, isPaused, nodeManagers.size(), busyNodes));
            break;
        case EXIT:
            //kill all the node managers and kill the local actor system and then exit
            nodeManagers.forEach((o) -> {
                NodeManagerCommand nodeManagerCommand = new NodeManagerCommand();
                nodeManagerCommand.setType(NodeManagerCommandType.REMOTE_EXIT);
                o.tell(nodeManagerCommand, getSelf());
            });
            context().stop(getSelf());
            break;
        default:
            unhandled(message);
        }
    }
}