Example usage for java.util.stream Collectors toMap

List of usage examples for java.util.stream Collectors toMap

Introduction

In this page you can find the example usage for java.util.stream Collectors toMap.

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

/**
 * Actually draws the environment on the view.
 * /*w w w  .j av  a 2s.  co m*/
 * @param g
 *            {@link Graphics2D} object responsible for drawing
 */
protected final void drawEnvOnView(final Graphics2D g) {
    if (wormhole == null || !isVisible() || !isEnabled()) {
        return;
    }
    accessData();
    if (hooked.isPresent()) {
        final Position hcoor = positions.get(hooked.get());
        final Point hp = wormhole.getViewPoint(hcoor);
        if (hp.distance(getCenter()) > FREEDOM_RADIUS) {
            wormhole.setViewPosition(hp);
        }
    }
    /*
     * Compute nodes in sight and their screen position
     */
    final Map<Node<T>, Point> onView = positions.entrySet().parallelStream()
            .map(pair -> new Pair<>(pair.getKey(), wormhole.getViewPoint(pair.getValue())))
            .filter(p -> wormhole.isInsideView(p.getSecond()))
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    g.setColor(Color.BLACK);
    if (obstacles != null) {
        /*
         * TODO: only draw obstacles if on view
         */
        obstacles.parallelStream().map(this::convertObstacle).forEachOrdered(g::fill);
    }
    if (paintLinks) {
        g.setColor(Color.GRAY);
        onView.keySet().parallelStream().map(neighbors::get)
                .flatMap(neigh -> neigh.getNeighbors().parallelStream()
                        .map(node -> node.compareTo(neigh.getCenter()) > 0 ? new Pair<>(neigh.getCenter(), node)
                                : new Pair<>(node, neigh.getCenter())))
                .distinct().map(
                        pair -> mapPair(pair,
                                node -> Optional.ofNullable(onView.get(node))
                                        .orElse(wormhole.getViewPoint(positions.get(node)))))
                .forEachOrdered(line -> {
                    final Point p1 = line.getFirst();
                    final Point p2 = line.getSecond();
                    g.drawLine(p1.x, p1.y, p2.x, p2.y);
                });
    }
    releaseData();
    if (isDraggingMouse && status == ViewStatus.MOVING && originPoint.isPresent() && endingPoint.isPresent()) {
        for (final Node<T> n : selectedNodes) {
            if (onView.containsKey(n)) {
                onView.put(n, new Point(onView.get(n).x + (endingPoint.get().x - originPoint.get().x),
                        onView.get(n).y + (endingPoint.get().y - originPoint.get().y)));
            }
        }
    }
    g.setColor(Color.GREEN);
    if (effectStack != null) {
        effectStack.forEach(effect -> {
            onView.entrySet().forEach(entry -> {
                final Point p = entry.getValue();
                effect.apply(g, entry.getKey(), p.x, p.y);
            });
        });
    }
    if (isCloserNodeMarked()) {
        final Optional<Map.Entry<Node<T>, Point>> closest = onView.entrySet().parallelStream()
                .min((pair1, pair2) -> {
                    final Point p1 = pair1.getValue();
                    final Point p2 = pair2.getValue();
                    final double d1 = Math.hypot(p1.x - mousex, p1.y - mousey);
                    final double d2 = Math.hypot(p2.x - mousex, p2.y - mousey);
                    return Double.compare(d1, d2);
                });
        if (closest.isPresent()) {
            nearest = closest.get().getKey();
            final int nearestx = closest.get().getValue().x;
            final int nearesty = closest.get().getValue().y;
            drawFriedEgg(g, nearestx, nearesty, Color.RED, Color.YELLOW);
        }
    } else {
        nearest = null;
    }
    if (isDraggingMouse && status == ViewStatus.SELECTING && originPoint.isPresent()
            && endingPoint.isPresent()) {
        g.setColor(Color.BLACK);
        final int x = originPoint.get().x < endingPoint.get().x ? originPoint.get().x : endingPoint.get().x;
        final int y = originPoint.get().y < endingPoint.get().y ? originPoint.get().y : endingPoint.get().y;
        final int width = Math.abs(endingPoint.get().x - originPoint.get().x);
        final int height = Math.abs(endingPoint.get().y - originPoint.get().y);
        g.drawRect(x, y, width, height);
        selectedNodes = onView.entrySet().parallelStream()
                .filter(nodes -> isInsideRectangle(nodes.getValue(), x, y, width, height))
                .map(onScreen -> onScreen.getKey()).collect(Collectors.toSet());
    }
    selectedNodes.parallelStream().map(e -> Optional.ofNullable(onView.get(e))).filter(Optional::isPresent)
            .map(Optional::get).forEachOrdered(p -> drawFriedEgg(g, p.x, p.y, Color.BLUE, Color.CYAN));
}

From source file:com.haulmont.cuba.gui.components.listeditor.ListEditorPopupWindow.java

protected LookupField createComponentForEnum() {
    if (enumClass == null) {
        throw new IllegalStateException("EnumClass parameter is not defined");
    }//from  w  w  w. ja  v  a 2s.  c  o  m
    LookupField lookupField = createLookupField();
    Enum[] enumConstants = enumClass.getEnumConstants();
    Map<String, Enum> enumValuesMap = Stream.of(enumConstants)
            .collect(Collectors.toMap(o -> messages.getMessage(o), Function.identity()));
    lookupField.setOptionsMap(enumValuesMap);
    return lookupField;
}

From source file:eu.itesla_project.simulation.ImpactAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    ComponentDefaultConfig config = new ComponentDefaultConfig();
    String caseFormat = line.getOptionValue("case-format");
    Path caseDir = Paths.get(line.getOptionValue("case-dir"));
    String caseBaseName = null;//from   ww  w  .ja  v  a2 s  .c  o  m
    if (line.hasOption("case-basename")) {
        caseBaseName = line.getOptionValue("case-basename");
    }
    final Set<String> contingencyIds = line.hasOption("contingencies")
            ? Sets.newHashSet(line.getOptionValue("contingencies").split(","))
            : null;
    Path outputCsvFile = null;
    if (line.hasOption("output-csv-file")) {
        outputCsvFile = Paths.get(line.getOptionValue("output-csv-file"));
    }

    try (ComputationManager computationManager = new LocalComputationManager()) {

        ContingenciesProvider contingenciesProvider = config
                .findFactoryImplClass(ContingenciesProviderFactory.class).newInstance().create();
        SimulatorFactory simulatorFactory = config.findFactoryImplClass(SimulatorFactory.class).newInstance();

        Importer importer = Importers.getImporter(caseFormat, computationManager);
        if (importer == null) {
            throw new ITeslaException("Format " + caseFormat + " not supported");
        }

        if (caseBaseName != null) {

            Multimap<String, SecurityIndex> securityIndexesPerContingency = runImpactAnalysis(caseDir,
                    caseBaseName, contingencyIds, importer, computationManager, simulatorFactory,
                    contingenciesProvider);

            if (securityIndexesPerContingency != null) {
                if (outputCsvFile == null) {
                    prettyPrint(securityIndexesPerContingency);
                } else {
                    writeCsv(securityIndexesPerContingency, outputCsvFile);
                }
            }
        } else {
            if (outputCsvFile == null) {
                throw new RuntimeException(
                        "In case of multiple impact analyses, only ouput to csv file is supported");
            }
            Map<String, Map<SecurityIndexId, SecurityIndex>> securityIndexesPerCase = new LinkedHashMap<>();
            Importers.importAll(caseDir, importer, false, network -> {
                try {
                    Multimap<String, SecurityIndex> securityIndexesPerContingency = runImpactAnalysis(network,
                            contingencyIds, computationManager, simulatorFactory, contingenciesProvider);
                    if (securityIndexesPerContingency == null) {
                        securityIndexesPerCase.put(network.getId(), null);
                    } else {
                        Map<SecurityIndexId, SecurityIndex> securityIndexesPerId = securityIndexesPerContingency
                                .values().stream().collect(Collectors.toMap(SecurityIndex::getId, e -> e));
                        securityIndexesPerCase.put(network.getId(), securityIndexesPerId);
                    }
                } catch (Exception e) {
                    LOGGER.error(e.toString(), e);
                }
            }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + "..."));

            writeCsv(securityIndexesPerCase, outputCsvFile);
        }
    }
}

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

@GET
@Path("/configuration/{configId}")
@Produces(MediaType.APPLICATION_JSON)//from  w  w w. j a v a 2s  .c  om
@RolesAllowed({ Authority.ADMINISTRATOR, Authority.MANAGER })
public Response getArchivedConfigServices(@PathParam("configId") String id) {

    try {
        byte[] gvcore = gvConfigurationManager.extract(id, "GVCore.xml");

        if (gvcore != null && gvcore.length > 0) {

            Document gvcoreDocument = documentBuilder.parse(new ByteArrayInputStream(gvcore));

            NodeList serviceNodes = XMLConfig.getNodeList(gvcoreDocument, "//Service");

            Map<String, ServiceDTO> services = IntStream.range(0, serviceNodes.getLength())
                    .mapToObj(serviceNodes::item).map(ServiceDTO::buildServiceFromConfig)
                    .filter(Optional::isPresent).map(Optional::get)
                    .collect(Collectors.toMap(ServiceDTO::getIdService, Function.identity()));

            LOG.debug("Services found " + serviceNodes.getLength());
            return Response.ok(toJson(services)).build();

        }

        return Response.status(Response.Status.NOT_FOUND).build();

    } catch (XMLConfigException | JsonProcessingException xmlConfigException) {
        LOG.error("Error reading services configuration", xmlConfigException);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(toJson(xmlConfigException)).build());
    } catch (Exception e) {
        LOG.error("Error reading services configuration", e);
        return Response.status(Response.Status.NOT_FOUND).build();

    }

}

From source file:gov.pnnl.goss.gridappsd.testmanager.CompareResults.java

/**
 * Get the map of the expected outputs//from ww w . ja v a  2s. c o m
 * @param expectedOutputPath
 * @return
 * @throws FileNotFoundException
 */
private Map<String, JsonElement> getExpectedOutputMap(String expectedOutputPath) {
    Map<String, JsonElement> expectedOutputMap = null;
    try {
        JsonParser parser = new JsonParser();
        JsonElement expectedOutputObj = parser.parse(new BufferedReader(new FileReader(expectedOutputPath)));
        if (expectedOutputObj.isJsonObject()) {
            JsonObject jsonObject = expectedOutputObj.getAsJsonObject();
            JsonObject output = jsonObject.get("expected_output").getAsJsonObject();
            JsonObject outputs = output.get("ieee8500").getAsJsonObject();
            expectedOutputMap = outputs.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()));
            System.out.println("     Lookup expected" + expectedOutputMap.get("rcon_VREG3"));

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return expectedOutputMap;
}

From source file:com.diversityarrays.kdxplore.trials.TrialSelectionDialog.java

public TrialSelectionDialog(Window owner, String title, DALClient c, List<Trial> kdxTrials,
        Transformer<BackgroundRunner, TrialSearchOptionsPanel> searchOptionsPanelFactory) {
    super(owner, title, USE_TRIALS);

    setGlassPane(backgroundRunner.getBlockingPane());

    searchOptionsPanel = searchOptionsPanelFactory.transform(backgroundRunner);
    helpInstructions = new JLabel(searchOptionsPanel.getHtmlHelp(GET_TRIALS));

    kdxTrialByIdDownloaded = kdxTrials.stream().filter(t -> t.getIdDownloaded() != null)
            .collect(Collectors.toMap(Trial::getIdDownloaded, java.util.function.Function.identity()));

    trialRecordTable.setName(this.getClass().getName() + ".trialRecordTable"); //$NON-NLS-1$

    TableColumnModel tcm = trialRecordTable.getColumnModel();
    TableCellRenderer cellRenderer = new OptionalCheckboxRenderer("Already downloaded");
    tcm.getColumn(trialRecordTableModel.getChosenColumnIndex()).setCellRenderer(cellRenderer);

    for (int col = tcm.getColumnCount(); --col >= 0;) {
        if ("TrialName".equals(trialRecordTable.getColumnName(col))) {
            TableColumn tc = tcm.getColumn(col);
            tc.setCellRenderer(new TrialNameCellRenderer());
            break;
        }/* w w  w. j a  v  a2 s  .com*/
    }

    findTrialRecords.setEnabled(false);

    searchOptionsPanel.addSearchOptionsChangeListener(searchOptionsListener);
    wantTrialUnits.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filteringClauseUsed = null;
            handleSearchOptionsChoiceChanged();
        }
    });

    setDALClient(c);

    initialiseGui();

    if (owner != null) {
        Dimension ownerSize = owner.getSize();
        Dimension mySize = getSize();
        int w = (ownerSize.width * 3) / 4;
        int h = (ownerSize.height * 3) / 4;
        if (w > mySize.width || h > mySize.height) {
            if (w > mySize.width) {
                mySize.width = w;
            }
            if (h > mySize.height) {
                mySize.height = h;
            }
            setSize(mySize);
        }
    }

    // TODO consider using setSize to increase to parent's width
    getOkAction().setEnabled(false);
    trialRecordTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            getOkAction().setEnabled(trialRecordTableModel.getAnyChosen());
        }
    });
}

From source file:pl.edu.icm.comac.vis.server.DataController.java

private void applyImportance(Map<URI, Map<String, Object>> nodes, Map<String, Double> importance) {
    Map<String, Map<String, Object>> snodes = nodes.entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey().stringValue(), e -> e.getValue()));//necessary to change key type.
    for (Map.Entry<String, Double> entry : importance.entrySet()) {
        Map<String, Object> node = snodes.get(entry.getKey());
        node.put(JSON_IMPORTANCE, "" + entry.getValue());
    }//from   w w  w .  j  av a 2 s  .c om
}

From source file:com.netflix.spinnaker.clouddriver.titus.client.RegionScopedTitusClient.java

@Override
public Map<String, String> getAllJobNames() {
    JobQuery.Builder jobQuery = JobQuery.newBuilder().putFilteringCriteria("jobType", "SERVICE")
            .putFilteringCriteria("attributes", "source:spinnaker").addFields("id")
            .addFields("jobDescriptor.attributes.name");

    List<com.netflix.titus.grpc.protogen.Job> grpcJobs = getJobsWithFilter(jobQuery, 10000);

    return grpcJobs.stream().collect(Collectors.toMap(com.netflix.titus.grpc.protogen.Job::getId,
            it -> it.getJobDescriptor().getAttributesOrDefault("name", "")));
}

From source file:eu.itesla_project.modules.simulation.ImpactAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    OfflineConfig config = OfflineConfig.load();
    String caseFormat = line.getOptionValue("case-format");
    Path caseDir = Paths.get(line.getOptionValue("case-dir"));
    String caseBaseName = null;/*from  w ww.  ja va 2  s  .c  om*/
    if (line.hasOption("case-basename")) {
        caseBaseName = line.getOptionValue("case-basename");
    }
    final Set<String> contingencyIds = line.hasOption("contingencies")
            ? Sets.newHashSet(line.getOptionValue("contingencies").split(","))
            : null;
    Path outputCsvFile = null;
    if (line.hasOption("output-csv-file")) {
        outputCsvFile = Paths.get(line.getOptionValue("output-csv-file"));
    }

    try (ComputationManager computationManager = new LocalComputationManager()) {

        DynamicDatabaseClientFactory ddbFactory = config.getDynamicDbClientFactoryClass().newInstance();
        ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass()
                .newInstance().create();
        SimulatorFactory simulatorFactory = config.getSimulatorFactoryClass().newInstance();

        Importer importer = Importers.getImporter(caseFormat, computationManager);
        if (importer == null) {
            throw new ITeslaException("Format " + caseFormat + " not supported");
        }

        if (caseBaseName != null) {

            Multimap<String, SecurityIndex> securityIndexesPerContingency = runImpactAnalysis(caseDir,
                    caseBaseName, contingencyIds, importer, computationManager, simulatorFactory, ddbFactory,
                    contingencyDb);

            if (securityIndexesPerContingency != null) {
                if (outputCsvFile == null) {
                    prettyPrint(securityIndexesPerContingency);
                } else {
                    writeCsv(securityIndexesPerContingency, outputCsvFile);
                }
            }
        } else {
            if (outputCsvFile == null) {
                throw new RuntimeException(
                        "In case of multiple impact analyses, only ouput to csv file is supported");
            }
            Map<String, Map<SecurityIndexId, SecurityIndex>> securityIndexesPerCase = new LinkedHashMap<>();
            Importers.importAll(caseDir, importer, false, network -> {
                try {
                    Multimap<String, SecurityIndex> securityIndexesPerContingency = runImpactAnalysis(network,
                            contingencyIds, computationManager, simulatorFactory, ddbFactory, contingencyDb);
                    if (securityIndexesPerContingency == null) {
                        securityIndexesPerCase.put(network.getId(), null);
                    } else {
                        Map<SecurityIndexId, SecurityIndex> securityIndexesPerId = securityIndexesPerContingency
                                .values().stream().collect(Collectors.toMap(SecurityIndex::getId, e -> e));
                        securityIndexesPerCase.put(network.getId(), securityIndexesPerId);
                    }
                } catch (Exception e) {
                    LOGGER.error(e.toString(), e);
                }
            }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + "..."));

            writeCsv(securityIndexesPerCase, outputCsvFile);
        }
    }
}