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:net.dv8tion.jda.managers.RoleManager.java

/**
 * Moves this Role up or down in the list of Roles (changing position attribute)
 * This change takes effect immediately!
 *
 * @param newPosition// w w w.j  a  v a2  s  .  c om
 *      the amount of positions to move up (offset &lt; 0) or down (offset &gt; 0)
 * @return
 *      this
 */
public RoleManager move(int newPosition) {
    checkPermission(Permission.MANAGE_ROLES);
    checkPosition();
    int maxRolePosition = role.getGuild().getRolesForUser(role.getJDA().getSelfInfo()).get(0).getPosition();
    if (newPosition >= maxRolePosition)
        throw new PermissionException(
                "Cannot move to a position equal to or higher than the highest role that you have access to.");

    if (newPosition < 0 || newPosition == role.getPosition())
        return this;

    Map<Integer, Role> newPositions = new HashMap<>();
    Map<Integer, Role> currentPositions = role.getGuild().getRoles().stream()
            .collect(Collectors.toMap(role -> role.getPosition(), role -> role));

    //Remove the @everyone role from our working set.
    currentPositions.remove(-1);
    int searchIndex = newPosition > role.getPosition() ? newPosition : newPosition;
    int index = 0;
    for (Role r : currentPositions.values()) {
        if (r == role)
            continue;
        if (index == searchIndex) {
            newPositions.put(index, role);
            index++;
        }
        newPositions.put(index, r);
        index++;
    }
    //If the role was moved to the very top, this will make sure it is properly handled.
    if (!newPositions.containsValue(role))
        newPositions.put(newPosition, role);

    for (int i = 0; i < newPositions.size(); i++) {
        if (currentPositions.get(i) == newPositions.get(i))
            newPositions.remove(i);
    }

    JSONArray rolePositions = new JSONArray();
    newPositions.forEach((pos, r) -> {
        rolePositions.put(new JSONObject().put("id", r.getId()).put("position", pos + 1));
    });
    ((JDAImpl) role.getJDA()).getRequester().patch(
            Requester.DISCORD_API_PREFIX + "guilds/" + role.getGuild().getId() + "/roles", rolePositions);
    return this;
}

From source file:com.epam.catgenome.manager.gene.GeneRegisterer.java

public GeneRegisterer(ReferenceGenomeManager referenceGenomeManager, FileManager fileManager,
        FeatureIndexManager featureIndexManager, GeneFile geneFile) {
    this.fileManager = fileManager;
    this.featureIndexManager = featureIndexManager;
    this.geneFile = geneFile;

    chromosomeMap = referenceGenomeManager.loadChromosomes(geneFile.getReferenceId()).stream()
            .collect(Collectors.toMap(BaseEntity::getName, c -> c));
}

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

public void loadSimResultTestCode(String path, SimulationOutput simOut) {
    JsonParser parser = new JsonParser();
    try {/*from  w w  w.  ja va2 s .  c om*/
        BufferedReader br = new BufferedReader(new FileReader(path));
        JsonElement elm = parser.parse(br);
        if (elm.isJsonObject()) {
            JsonObject jsonObject = elm.getAsJsonObject();
            JsonObject output = jsonObject.get("output").getAsJsonObject();
            JsonObject f2 = output.get("ieee8500").getAsJsonObject();

            // Turn to a Map 
            Map<String, JsonElement> ouputsMap = f2.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()));

            for (SimulationOutputObject out : simOut.output_objects) {
                JsonElement outputTmp = ouputsMap.get(out.name);
                System.out.println(out.name + " " + ouputsMap.get(out.name));
                // TODO Compare here since I can look at each output and property
                if (output != null) {
                    for (String prop : out.getProperties()) {
                        System.out.println("     " + prop);
                        System.out.println("     " + outputTmp.getAsJsonObject().get(prop));
                    }
                }
                break;
            }

            //             Set<Entry<String, JsonElement>> entrySet = f2.entrySet();          
            //             for(Map.Entry<String,JsonElement> entry : entrySet){
            //                if(entry.getValue().isJsonObject()){
            //                   JsonObject obj = entry.getValue().getAsJsonObject();
            //                   for (String prop : propsArray) {
            //                      if (obj.has(prop)) System.out.println(prop +  " : " + obj.get(prop));   
            //                  } 
            //
            //                }
            //                 System.out.println("key >>> "+entry.getKey());
            //                 System.out.println("val >>> "+entry.getValue());
            //             }

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

From source file:com.uber.okbuck.core.util.ProjectUtil.java

public static Map<ComponentIdentifier, ResolvedArtifactResult> downloadSources(Project project,
        Set<ResolvedArtifactResult> artifacts) {

    // Download sources if enabled via intellij extension
    if (!ProjectUtil.getOkBuckExtension(project).getIntellijExtension().downloadSources()) {
        return new HashMap<>();
    }//from w w  w  .  j  a va2 s  . c  o m

    DependencyHandler dependencies = project.getDependencies();

    try {
        Set<ComponentIdentifier> identifiers = artifacts.stream()
                .filter(artifact -> canHaveSources(artifact.getFile()))
                .map(artifact -> artifact.getId().getComponentIdentifier()).collect(Collectors.toSet());

        @SuppressWarnings("unchecked")
        Class<? extends Artifact>[] artifactTypesArray = (Class<? extends Artifact>[]) new Class<?>[] {
                SourcesArtifact.class };

        Set<ComponentArtifactsResult> results = dependencies.createArtifactResolutionQuery()
                .forComponents(identifiers).withArtifacts(JvmLibrary.class, artifactTypesArray).execute()
                .getResolvedComponents();

        // Only has one type.
        Class<? extends Artifact> type = artifactTypesArray[0];

        return results.stream().map(artifactsResult -> artifactsResult.getArtifacts(type)).flatMap(Set::stream)
                .filter(artifactResult -> artifactResult instanceof ResolvedArtifactResult)
                .map(artifactResult -> (ResolvedArtifactResult) artifactResult)
                .filter(artifactResult -> FileUtil.isZipFile(artifactResult.getFile()))
                .collect(Collectors.toMap(resolvedArtifact -> resolvedArtifact.getId().getComponentIdentifier(),
                        resolvedArtifact -> resolvedArtifact));

    } catch (Throwable t) {
        System.out.println(
                "Unable to download sources for project " + project.toString() + " with error " + t.toString());

        return new HashMap<>();
    }
}

From source file:de.whs.poodle.repositories.StatisticsRepository.java

public Map<Integer, Statistic> getExerciseToStatisticMapForSelfStudy(int studentId, int courseTermId) {
    @SuppressWarnings("unchecked")
    List<Statistic> statistics = em
            .createNativeQuery("SELECT s.* FROM self_study_worksheet_to_exercise wse "
                    + "JOIN student_to_course_term sct ON sct.id = wse.student_to_course_term_id "
                    + "JOIN exercise e ON wse.exercise_id = e.id "
                    + "JOIN v_statistic s ON s.exercise_root_id = e.root_id AND sct.student_id = s.student_id "
                    + "WHERE s.student_id = :studentId AND sct.course_term_id = :courseTermId", Statistic.class)
            .setParameter("courseTermId", courseTermId).setParameter("studentId", studentId).getResultList();

    return statistics.stream().collect(Collectors.toMap(Statistic::getExerciseRootId, Function.identity()));
}

From source file:com.github.horrorho.liquiddonkey.settings.commandline.CommandLineOptions.java

static Map<String, Property> optToProperty(Map<Property, Option> options) {
    return options.entrySet().stream()
            .map(set -> Arrays.asList(new SimpleEntry<>(set.getValue().getOpt(), set.getKey()),
                    new SimpleEntry<>(set.getValue().getLongOpt(), set.getKey())))
            .flatMap(List::stream).filter(set -> set.getKey() != null)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = { "/", "index" })
public String index(Model model, HttpServletRequest request) {

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        float males = fireFighterRepository.countByGender("m");
        float females = fireFighterRepository.countByGender("w");
        float sumFighters = males + females;
        float percentFem = females / sumFighters * 100;
        float percentMal = males / sumFighters * 100;
        percentFem = BigDecimal.valueOf(percentFem).setScale(2, RoundingMode.HALF_UP).floatValue();
        percentMal = BigDecimal.valueOf(percentMal).setScale(2, RoundingMode.HALF_UP).floatValue();
        model.addAttribute("males", percentMal);
        model.addAttribute("females", percentFem);
        model.addAttribute("sumFighters", sumFighters);
        List<Object[]> topFireBrigades = fireFighterRepository.groupByFireBrigade();
        Map<String, BigInteger> topFireBrigadesMap = topFireBrigades.stream().collect(Collectors.toMap(
                a -> (String) fireBrigadeRepository.findById((int) a[1]).getName(), a -> (BigInteger) a[0]));
        Map<String, BigInteger> sortedTopFireBrigadesMap = MapUtil.sortByValue(topFireBrigadesMap);
        model.addAttribute("sortedTopFireBrigades", sortedTopFireBrigadesMap);

    } else if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")
            && (request.isUserInRole("ROLE_ADMIN") || request.isUserInRole("ROLE_USER"))) {
        List<FireFighterModel> fireFighters = fireFighterRepository.findByFireBrigade(getSessionFireBrigade());
        model.addAttribute("fireFighters", fireFighters);
    }/*w  w w  .  j  ava 2 s  .  c om*/
    return "index";
}

From source file:io.yields.math.framework.kpi.ExplorerJsonExporter.java

private List<StatDefinition> buildStatDefinitions(List<Stats> stats,
        Function<String, String> explanationProvider) {

    Optional<Stats> template = stats.stream().findAny();
    Map<String, StatDefinition> roots = new HashMap<>();
    if (template.isPresent()) {
        Stats statsTemplate = template.get();
        Map<String, DoubleSummaryStatistics> summaries = statsTemplate.getStatsNames().stream()
                .collect(Collectors.toMap(Function.identity(), name -> getStats(name, stats)));
        summaries.keySet().stream().forEach(name -> {
            String values[] = name.split("#");
            double refLevel = statsTemplate.getRefLevel(name);
            double min = summaries.get(name).getMin();
            double max = summaries.get(name).getMax();
            if (Math.abs(max - min) < 2 * EPS) {
                min -= EPS;/*from w  ww. ja v a  2s  .  c om*/
                max += EPS;
            }
            if (values.length == 1) {
                roots.put(name, new StatDefinition(null, name, explanationProvider.apply(name),
                        Math.min(refLevel, min), Math.max(max, refLevel), refLevel));
            } else {
                StatDefinition root = roots.get(values[0]);
                if (root == null) {
                    root = new StatDefinition(values[0]);
                    roots.put(root.getName(), root);
                }
                StatDefinition element = root;
                for (int i = 1; i < values.length; i++) {
                    element = DefinitionBuilder.addChild(element, new StatDefinition(element, values[i],
                            Math.min(refLevel, min), Math.max(max, refLevel), refLevel));
                }
                element.setDescription(explanationProvider.apply(name));
            }
        });
    }

    return new ArrayList<>(roots.values());
}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBeanTest.java

public void testDoCreateXslExportInvalidToken() throws AccessDeniedException, IOException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(/*from  ww w.  ja v  a2s .co  m*/
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    String randomName = getRandomName();
    Map<String, String[]> parameters = new HashMap<>();
    parameters.put("title", new String[] { randomName });
    parameters.put("description", new String[] { randomName });
    parameters.put("extension", new String[] { randomName });
    parameters.put(SecurityTokenService.PARAMETER_TOKEN, new String[] {
            SecurityTokenService.getInstance().getToken(request, "admin/xsl/create_xsl_export.html") + "b" });
    Map<String, List<FileItem>> multipartFiles = new HashMap<>();
    List<FileItem> fileItems = new ArrayList<>();
    FileItem item = new DiskFileItemFactory().createItem("id_file", "", false, "xsl");
    item.getOutputStream().write("<?xml version='1.0'?><a/>".getBytes());
    fileItems.add(item);
    multipartFiles.put("id_file", fileItems);

    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);
    try {
        _instance.doCreateXslExport(new MultipartHttpServletRequest(request, multipartFiles, parameters));
        fail("Should have thrown");
    } catch (AccessDeniedException ade) {
        assertFalse(XslExportHome.getList().stream().anyMatch(e -> randomName.equals(e.getTitle())
                && randomName.equals(e.getDescription()) && randomName.equals(e.getExtension())));
    } finally {
        XslExportHome.getList().stream().filter(e -> randomName.equals(e.getTitle()))
                .forEach(e -> XslExportHome.remove(e.getIdXslExport()));
    }
}