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.netflix.spinnaker.fiat.roles.ldap.LdapUserRolesProvider.java

@Override
public Map<String, Collection<Role>> multiLoadRoles(Collection<String> userIds) {
    if (StringUtils.isEmpty(configProps.getGroupSearchBase())) {
        return new HashMap<>();
    }/*from  w ww . ja v  a 2  s.c o m*/

    // ExternalUser is used here as a simple data type to hold the username/roles combination.
    return userIds.stream().map(userId -> new ExternalUser().setId(userId).setExternalRoles(loadRoles(userId)))
            .collect(Collectors.toMap(ExternalUser::getId, ExternalUser::getExternalRoles));
}

From source file:com.hurence.logisland.connect.opc.CommonOpcSourceTask.java

@Override
public void start(Map<String, String> props) {
    setConfigurationProperties(props);/*from www .ja v a 2s .c o m*/

    transferQueue = new LinkedTransferQueue<>();
    opcOperations = new SmartOpcOperations<>(createOpcOperations());
    ConnectionProfile connectionProfile = createConnectionProfile();
    host = connectionProfile.getConnectionUri().getHost();
    tagInfoMap = CommonUtils.parseTagsFromProperties(props).stream()
            .collect(Collectors.toMap(TagInfo::getTagId, Function.identity()));
    minWaitTime = Math.min(10, tagInfoMap.values().stream().map(TagInfo::getSamplingInterval)
            .mapToLong(Duration::toMillis).min().getAsLong());
    opcOperations.connect(connectionProfile);
    if (!opcOperations.awaitConnected()) {
        throw new ConnectException("Unable to connect");
    }

    //set up polling source emission
    pollingScheduler = Executors.newSingleThreadScheduledExecutor();
    streamingThread = Executors.newSingleThreadExecutor();
    Map<Duration, List<TagInfo>> pollingMap = tagInfoMap.values().stream()
            .filter(tagInfo -> StreamingMode.POLL.equals(tagInfo.getStreamingMode()))
            .collect(Collectors.groupingBy(TagInfo::getSamplingInterval));
    final Map<String, OpcData> lastValues = Collections.synchronizedMap(new HashMap<>());
    pollingMap.forEach((k, v) -> pollingScheduler.scheduleAtFixedRate(() -> {
        final Instant now = Instant.now();
        v.stream().map(TagInfo::getTagId).map(lastValues::get).filter(Functions.not(Objects::isNull))
                .map(data -> Pair.of(now, data)).forEach(transferQueue::add);

    }, 0, k.toNanos(), TimeUnit.NANOSECONDS));
    //then subscribe for all
    final SubscriptionConfiguration subscriptionConfiguration = new SubscriptionConfiguration()
            .withDefaultSamplingInterval(Duration.ofMillis(10_000));
    tagInfoMap.values().forEach(tagInfo -> subscriptionConfiguration
            .withTagSamplingIntervalForTag(tagInfo.getTagId(), tagInfo.getSamplingInterval()));
    running.set(true);
    streamingThread.submit(() -> {
        while (running.get()) {
            try {
                createSessionIfNeeded();
                if (session == null) {
                    return;
                }

                session.stream(subscriptionConfiguration,
                        tagInfoMap.keySet().toArray(new String[tagInfoMap.size()])).forEach(opcData -> {
                            if (tagInfoMap.get(opcData.getTag()).getStreamingMode()
                                    .equals(StreamingMode.SUBSCRIBE)) {
                                transferQueue.add(Pair.of(
                                        hasServerSideSampling() ? opcData.getTimestamp() : Instant.now(),
                                        opcData));
                            } else {
                                lastValues.put(opcData.getTag(), opcData);
                            }
                        });
            } catch (Exception e) {
                if (running.get()) {
                    logger.warn("Stream interrupted while reading from " + host, e);
                    safeCloseSession();
                    lastValues.clear();

                }
            }
        }
    });

}

From source file:se.uu.it.cs.recsys.constraint.builder.ScheduleDomainBuilder.java

/**
 * For period 1 to 6. Periods 5, 6 are considered to have same domain as 1,
 * 2 respectively./* w  ww.j  a  v  a  2 s  .co  m*/
 *
 * @param periodsInfo
 * @return
 */
public Map<Integer, Set<Integer>> getStartPeriodAndIdSetMapping(Set<CourseSchedule> periodsInfo) {

    return getTaughtYearAndStartPeriodToIdMapping(periodsInfo).entrySet().stream()
            .collect(Collectors.toMap(periodInfo -> {
                return (int) periodInfo.getKey().getPeriodIdxAmongAllPlanPeriods();
            }, Map.Entry::getValue));
}

From source file:com.coinblesk.server.controller.AdminController.java

@RequestMapping(value = "/keys", method = GET)
@ResponseBody//  w  w  w .  j ava  2s  .c  om
public List<KeysDTO> getAllKeys() {
    NetworkParameters params = appConfig.getNetworkParameters();

    // Pre-calculate balances for each address
    Map<Address, Coin> balances = walletService.getBalanceByAddresses();

    List<Keys> keys = keyService.allKeys();

    // ...and summed for each public key
    Map<Keys, Long> balancesPerKeys = keys.stream()
            .collect(Collectors.toMap(Function.identity(), key -> key.timeLockedAddresses().stream()
                    .map(tla -> tla.toAddress(params)).map(balances::get).mapToLong(Coin::longValue).sum()));

    // Map the Keys entities to DTOs including the containing TimeLockedAddresses
    return keys.stream().map(key -> new KeysDTO(SerializeUtils.bytesToHex(key.clientPublicKey()),
            SerializeUtils.bytesToHex(key.serverPublicKey()), SerializeUtils.bytesToHex(key.serverPrivateKey()),
            Date.from(Instant.ofEpochSecond(key.timeCreated())), key.virtualBalance(), balancesPerKeys.get(key),
            key.virtualBalance() + balancesPerKeys.get(key), key.timeLockedAddresses().stream().map(tla -> {
                Instant createdAt = Instant.ofEpochSecond(tla.getTimeCreated());
                Instant lockedUntil = Instant.ofEpochSecond(tla.getLockTime());
                Coin balance = balances.get(tla.toAddress(params));
                return new TimeLockedAddressDTO(tla.toAddress(params).toString(),
                        "http://" + (params.getClass().equals(TestNet3Params.class) ? "tbtc." : "")
                                + "blockr.io/address/info/" + tla.toAddress(params),
                        Date.from(createdAt), Date.from(lockedUntil), lockedUntil.isAfter(Instant.now()),
                        balance.longValue());
            }).collect(Collectors.toList()))).collect(Collectors.toList());
}

From source file:bjerne.gallery.service.impl.GalleryAuthorizationServiceSSImpl.java

private Map<String, File> getRootPathsForRoles(Collection<String> roles, Collection<GalleryRootDir> rootDirs) {
    Map<String, File> rootPathsForRoles = rootDirs.stream().filter(r -> roles.contains(r.getRole()))
            .collect(Collectors.toMap(GalleryRootDir::getName, GalleryRootDir::getDir));
    LOG.debug("Root paths for roles {}: {}", roles, rootPathsForRoles);
    return rootPathsForRoles;
}

From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java

private static <T> Map<String, List<T>> _flattenMap(Map<String, Map<Integer, T>> indexedValueLists) {

    Set<Entry<String, Map<Integer, T>>> entries = indexedValueLists.entrySet();

    Stream<Entry<String, Map<Integer, T>>> stream = entries.stream();

    return stream.collect(Collectors.toMap(Entry::getKey, v -> {
        Map<Integer, T> map = v.getValue();

        return new ArrayList<>(map.values());
    }));/*from  w ww .  jav  a 2  s.c om*/
}

From source file:nl.rivm.cib.episim.cbs.CBSConnectorTest.java

@Test
public void testOlingo() throws IOException {
    final String serviceUrl = "http://opendata.cbs.nl/ODataApi/odata/83225ned";//"http://opendata.cbs.nl/ODataApi/odata/81435ned";
    final Edm edm = ODataUtil.readEdm(serviceUrl);
    edm.getSchemas().forEach(s -> {/*from w  w  w .  j av a2  s .c  om*/
        s.getEntityTypes().forEach(t -> {
            t.getPropertyNames().forEach(p -> {
                if (p.equals("Key"))
                    System.err.println(ODataUtil.readEntities(edm, serviceUrl, t.getName() + "$select="));
                LOG.trace("{}.{} :: {} ({})", t.getNamespace(), t.getName(), p, t.getProperty(p).getType());
            });
        });
        //         final Map<Object, Object> dims = s.getEntityTypes().stream().filter( e->e.getPropertyNames().contains( "Key" ) )
        //               .collect( Collectors.toMap(
        //                     e -> e.getProperty( "Key" ),
        //                     e -> e.getProperty( "Title" ) ) );
        //         LOG.trace( "{} dims: {}", s.getNamespace(), dims );

        final String dim = "Geslacht";
        final Map<Object, Object> keys = StreamSupport
                .stream(Spliterators.spliteratorUnknownSize(ODataUtil.readEntities(edm, serviceUrl, dim),
                        Spliterator.CONCURRENT), false)
                .collect(Collectors.toMap(e -> e.getProperty("Key").getPrimitiveValue().toValue(),
                        e -> e.getProperty("Title").getPrimitiveValue().toValue()));
        LOG.trace("{} keys: {}", dim, keys);
    });

}

From source file:org.fenixedu.academic.thesis.ui.controller.StudentCandidaciesController.java

@RequestMapping(value = "", method = RequestMethod.GET)
public String listProposals(Model model) {

    Student student = Authenticate.getUser().getPerson().getStudent();

    Set<ThesisProposalsConfiguration> suggestedConfigs = service.getSuggestedConfigs(student);

    HashMap<Registration, Set<ThesisProposal>> proposalsByReg = service.getOpenProposalsByReg(student);

    Map<ThesisProposalsConfiguration, List<StudentThesisCandidacy>> candidaciesByConfig = service
            .getCandidaciesByConfig(student);

    int proposalsSize = proposalsByReg.values().stream().map(Set::size).reduce(0, (a, b) -> a + b);
    int candidaciesSize = candidaciesByConfig.values().stream().map(List::size).reduce(0, (a, b) -> a + b);

    if (participantLabelService != null) {
        model.addAttribute("participantLabelService", participantLabelService);
    }// w  w  w  .jav a2  s . c o  m

    model.addAttribute("suggestedConfigs", suggestedConfigs);
    model.addAttribute("proposalsSize", proposalsSize);
    model.addAttribute("candidaciesSize", candidaciesSize);
    model.addAttribute("candidaciesByConfig", candidaciesByConfig);
    model.addAttribute("proposalsByReg", proposalsByReg);

    Map<ThesisProposal, Integer> applicationCountByProposalConfig = candidaciesByConfig.values().stream()
            .flatMap(List::stream).collect(Collectors.toMap(StudentThesisCandidacy::getThesisProposal,
                    c -> c.getThesisProposal().getStudentThesisCandidacySet().size()));
    model.addAttribute("applicationCountByProposalConfig", applicationCountByProposalConfig);

    Map<ThesisProposal, Integer> applicationCountByProposalReg = proposalsByReg.values().stream()
            .flatMap(Set::stream)
            .collect(Collectors.toMap(tp -> tp, tp -> tp.getStudentThesisCandidacySet().size()));
    model.addAttribute("applicationCountByProposalReg", applicationCountByProposalReg);

    Set<ThesisProposal> acceptedProposals = proposalsByReg.values().stream().flatMap(Set::stream)
            .flatMap(tp -> tp.getStudentThesisCandidacySet().stream())
            .filter(candidacy -> candidacy.getAcceptedByAdvisor())
            .map(candidacy -> candidacy.getThesisProposal()).collect(Collectors.toSet());
    model.addAttribute("acceptedProposals", acceptedProposals);

    return "studentCandidacies/list";
}

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

protected void initValues() {
    if (values == null) {
        values = new ArrayList<>();
    }//from   www  .ja v a2 s  .  c  o  m

    valuesMap = values.stream().collect(Collectors.toMap(Function.identity(),
            o -> ListEditorHelper.getValueCaption(o, itemType, timeZone)));

    for (Map.Entry<Object, String> entry : valuesMap.entrySet()) {
        addValueToLayout(entry.getKey(), entry.getValue());
    }
}

From source file:eu.crydee.alignment.aligner.ae.MetricsOneVsOneC.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);
    results = HashBasedTable.create();/* w  ww.j  ava  2  s.  c  om*/
    keys = Lists.newArrayList(keysArray);
    methodsMetadata = Arrays.stream(Complete.class.getMethods())
            .map(m -> Pair.of(m, m.getAnnotation(Metric.class)))
            .filter(p -> p.getRight() != null && keys.contains(p.getRight().key()))
            .collect(Collectors.toMap(p -> p.getRight().key(), p -> Pair.of(p.getLeft(), p.getRight().name())));
}