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:com.spankingrpgs.model.GameState.java

/**
 * Returns an unmodifiable version of the active party
 *
 * @return An unmodifiable copy of the active party
 *///from  w ww  . java2  s. c om
@JsonIgnore
public Map<CombatRange, List<GameCharacter>> getParty() {
    return party.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, rangeCharacters -> rangeCharacters.getValue().stream()
                    .map(this::getCharacter).collect(Collectors.toList())));
}

From source file:com.diversityarrays.kdxplore.data.kdx.CurationData.java

private void addSamplesFromSampleGroup(SampleGroup sampleGroup) {
    if (sampleGroup == null) {
        return;/*w  w w.j a  v  a  2s  .  c om*/
    }

    Map<String, TraitInstance> traitInstanceByIdent = traitInstances.stream().collect(
            Collectors.toMap((ti) -> InstanceIdentifierUtil.getInstanceIdentifier(ti), Function.identity()));

    for (KdxSample s : sampleGroup.getSamples()) {
        String ident = InstanceIdentifierUtil.getInstanceIdentifier(s);
        TraitInstance ti = traitInstanceByIdent.get(ident);
        if (ti == null) {

        }
        CurationCellId ccid = curationCellIdFactory.getCurationCellId(ti, s);
        List<KdxSample> list = samplesByCurationCellId.get(ccid);
        if (list == null) {
            list = new ArrayList<>();
            samplesByCurationCellId.put(ccid, list);
        }
        list.add(s);
    }
}

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

public void testDoRemoveXslExport() throws AccessDeniedException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(//w w  w  .  ja  va 2  s.  co m
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    request.setParameter("id_xsl_export", Integer.toString(_xslExport.getIdXslExport()));
    request.setParameter(SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance().getToken(request, "jsp/admin/xsl/DoRemoveXslExport.jsp"));
    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    _instance.doRemoveXslExport(request);

    XslExport stored = XslExportHome.findByPrimaryKey(_xslExport.getIdXslExport());
    assertNull(stored);
}

From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java

@Override
public void afterPropertiesSet() throws IOException {
    instanceTypes = csvForBean.toBean(InstanceType.class, "csv/instance-type-details.csv").stream()
            .collect(Collectors.toMap(InstanceType::getId, Function.identity()));

}

From source file:com.spankingrpgs.model.GameState.java

/**
 * Returns a mapping from combat range to a list of character names, which is then serialized by Jackson to save the
 * current party.//from  w  w w . j av a2  s.c o m
 *
 * @return A mapping from CombatRange to a list of character names in the party at that range
 */
@JsonProperty("party")
public Map<CombatRange, List<String>> getSerializedParty() {
    return Collections.unmodifiableMap(getParty().entrySet().stream().collect(Collectors.toMap(
            Map.Entry::getKey,
            entry -> entry.getValue().stream().map(GameCharacter::getName).collect(Collectors.toList()))));
}

From source file:cn.org.once.cstack.service.impl.ModuleServiceImpl.java

public Map<ModuleEnvironmentRole, ModuleEnvironmentVariable> getModuleEnvironmentVariables(Image image,
        String applicationName) {
    return image.getModuleEnvironmentVariables().entrySet().stream()
            .collect(Collectors.toMap(kv -> kv.getKey(), kv -> {
                String value = null;
                switch (kv.getKey()) {
                case USER:
                    value = ModuleUtils.generateRamdomUser();
                    break;
                case PASSWORD:
                    value = ModuleUtils.generateRamdomPassword();
                    break;
                case NAME:
                    value = applicationName;
                    break;
                }/*  w  w  w .  j ava 2  s  .c  om*/
                return new ModuleEnvironmentVariable(kv.getValue(), value);
            }));
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_LibraryJars.java

/** Gets a list of _id,modified from v1 and a list matching _id,modified from V2
 * @param library_mgmt/*from w  ww.j av a  2s. c om*/
 * @param share_db
 * @return tuple of id-vs-(date-or-null-if-not-approved) for v1, id-vs-date for v2
 */
protected static CompletableFuture<Tuple2<Map<String, String>, Map<String, Date>>> compareJarsToLibaryBeans_get(
        final IManagementCrudService<SharedLibraryBean> library_mgmt, final ICrudService<JsonNode> share_db) {
    // (could make this more efficient by having a regular "did something happen" query with a slower "get everything and resync)
    // (don't forget to add "modified" to the compound index though)
    CompletableFuture<Cursor<JsonNode>> f_v1_jars = share_db
            .getObjectsBySpec(CrudUtils.allOf().when("type", "binary").rangeIn("title", "/app/aleph2/library/",
                    true, "/app/aleph2/library0", true), Arrays.asList(JsonUtils._ID, "modified"), true);

    return f_v1_jars.<Map<String, String>>thenApply(v1_jars -> {
        return StreamSupport.stream(v1_jars.spliterator(), false).collect(Collectors
                .toMap(j -> safeJsonGet(JsonUtils._ID, j).asText(), j -> safeJsonGet("modified", j).asText()));
    }).<Tuple2<Map<String, String>, Map<String, Date>>>thenCompose(v1_id_datestr_map -> {
        final SingleQueryComponent<SharedLibraryBean> library_query = CrudUtils.allOf(SharedLibraryBean.class)
                .rangeIn(SharedLibraryBean::_id, "v1_", true, "v1a", true);

        return library_mgmt.getObjectsBySpec(library_query, Arrays.asList(JsonUtils._ID, "modified"), true)
                .<Tuple2<Map<String, String>, Map<String, Date>>>thenApply(c -> {
                    final Map<String, Date> v2_id_date_map = StreamSupport.stream(c.spliterator(), false)
                            .collect(Collectors.toMap(b -> b._id().substring(3), //(ie remove the "v1_")
                                    b -> b.modified()));

                    return Tuples._2T(v1_id_datestr_map, v2_id_date_map);
                });
    });
}

From source file:alfio.manager.CheckInManager.java

public Map<String, String> getEncryptedAttendeesInformation(Event ev, Set<String> additionalFields,
        List<Integer> ids) {

    return Optional.ofNullable(ev).filter(isOfflineCheckInEnabled()).map(event -> {
        Map<Integer, TicketCategory> categories = ticketCategoryRepository.findByEventIdAsMap(event.getId());
        String eventKey = event.getPrivateKey();

        Function<FullTicketInfo, String> hashedHMAC = ticket -> DigestUtils
                .sha256Hex(ticket.hmacTicketInfo(eventKey));

        Function<FullTicketInfo, String> encryptedBody = ticket -> {
            Map<String, String> info = new HashMap<>();
            info.put("firstName", ticket.getFirstName());
            info.put("lastName", ticket.getLastName());
            info.put("fullName", ticket.getFullName());
            info.put("email", ticket.getEmail());
            info.put("status", ticket.getStatus().toString());
            info.put("uuid", ticket.getUuid());
            info.put("category", ticket.getTicketCategory().getName());
            if (!additionalFields.isEmpty()) {
                Map<String, String> map = ticketFieldRepository
                        .findValueForTicketId(ticket.getId(), additionalFields).stream()
                        .collect(Collectors.toMap(TicketFieldValue::getName, TicketFieldValue::getValue));
                info.put("additionalInfoJson", Json.toJson(map));
            }//from   w  w  w .  j a va2s  . c  o m

            //
            TicketCategory tc = categories.get(ticket.getCategoryId());
            if (tc.getValidCheckInFrom() != null) {
                info.put("validCheckInFrom",
                        Long.toString(tc.getValidCheckInFrom(event.getZoneId()).toEpochSecond()));
            }
            if (tc.getValidCheckInTo() != null) {
                info.put("validCheckInTo",
                        Long.toString(tc.getValidCheckInTo(event.getZoneId()).toEpochSecond()));
            }
            //
            String key = ticket.ticketCode(eventKey);
            return encrypt(key, Json.toJson(info));
        };
        return ticketRepository.findAllFullTicketInfoAssignedByEventId(event.getId(), ids).stream()
                .collect(Collectors.toMap(hashedHMAC, encryptedBody));

    }).orElseGet(Collections::emptyMap);
}

From source file:org.obiba.mica.access.service.DataAccessRequestService.java

private void fillPdfTemplateFromRequest(byte[] template, OutputStream output, Object content)
        throws IOException, DocumentException {
    Map<String, Object> requestValues = PdfUtils.getFieldNames(template).stream()
            .map(k -> getMapEntryFromContent(content, k)) //
            .filter(e -> e != null && !e.getValue().isEmpty()) //
            .map(e -> Maps.immutableEntry(e.getKey(), e.getValue().get(0))) //
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    PdfUtils.fillOutForm(template, output, requestValues);
}

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

public void testDoRemoveXslExportInvalidToken() throws AccessDeniedException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    AdminUser user = new AdminUser();
    user.setRoles(/*  w w w.ja  v  a2s . com*/
            AdminRoleHome.findAll().stream().collect(Collectors.toMap(AdminRole::getKey, Function.identity())));
    Utils.registerAdminUserWithRigth(request, user, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    request.setParameter("id_xsl_export", Integer.toString(_xslExport.getIdXslExport()));
    request.setParameter(SecurityTokenService.PARAMETER_TOKEN,
            SecurityTokenService.getInstance().getToken(request, "jsp/admin/xsl/DoRemoveXslExport.jsp") + "b");
    _instance.init(request, XslExportJspBean.RIGHT_MANAGE_XSL_EXPORT);

    try {
        _instance.doRemoveXslExport(request);
        fail("Should have thrown");
    } catch (AccessDeniedException e) {
        XslExport stored = XslExportHome.findByPrimaryKey(_xslExport.getIdXslExport());
        assertNotNull(stored);
    }
}