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.steelbridgelabs.oss.neo4j.Neo4JTestGraphProvider.java

@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName,
        LoadGraphWith.GraphData graphData) {
    // build configuration
    Configuration configuration = Neo4JGraphConfigurationBuilder.connect("localhost", "neo4j", "123")
            .withName(graphName).withElementIdProvider(ElementIdProvider.class).build();
    // create property map from configuration
    Map<String, Object> map = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(configuration.getKeys(),
                    Spliterator.NONNULL | Spliterator.IMMUTABLE), false)
            .collect(Collectors.toMap(key -> key, configuration::getProperty));
    // append class name
    map.put(Graph.GRAPH, Neo4JGraph.class.getName());
    // return configuration map
    return map;/*from ww w. j a  v  a  2 s  . c om*/
}

From source file:alfio.manager.EventStatisticsManager.java

public List<EventStatistic> getAllEventsWithStatisticsFilteredBy(String username, Predicate<Event> predicate) {
    List<Event> events = getAllEvents(username).stream().filter(predicate).collect(toList());
    Map<Integer, Event> mappedEvent = events.stream()
            .collect(Collectors.toMap(Event::getId, Function.identity()));
    if (!mappedEvent.isEmpty()) {
        boolean isOwner = userManager.isOwner(userManager.findUserByUsername(username));
        Set<Integer> ids = mappedEvent.keySet();
        Stream<EventStatisticView> stats = isOwner ? eventRepository.findStatisticsFor(ids).stream()
                : ids.stream().map(EventStatisticView::empty);
        return stats.map(stat -> {
            Event event = mappedEvent.get(stat.getEventId());
            return new EventStatistic(event, stat, displayStatisticsForEvent(event));
        }).sorted().collect(Collectors.toList());
    } else {//ww w . ja  v  a  2  s  .c  o m
        return Collections.emptyList();
    }
}

From source file:mtsar.processors.task.InverseCountAllocator.java

@Override
@Nonnull/*from   www .  ja  v  a  2 s  . c o m*/
public Optional<TaskAllocation> allocate(@Nonnull Worker worker, @Nonnegative int n) {
    requireNonNull(stage, "the stage provider should not provide null");
    final Set<Integer> answered = answerDAO.listForWorker(worker.getId(), stage.getId()).stream()
            .map(Answer::getTaskId).collect(Collectors.toSet());

    final Map<Integer, Integer> counts = countDAO.getCountsSQL(stage.getId()).stream()
            .filter(pair -> !answered.contains(pair.getKey()))
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));

    final List<Integer> ids = filterTasks(counts);
    final int taskRemaining = ids.size();

    if (ids.isEmpty())
        return Optional.empty();
    if (taskRemaining > n)
        ids.subList(n, ids.size()).clear();
    final List<Task> tasks = taskDAO.select(ids, stage.getId());

    final int taskCount = taskDAO.count(stage.getId());
    final TaskAllocation allocation = new TaskAllocation.Builder().setWorker(worker).addAllTasks(tasks)
            .setTaskRemaining(taskRemaining).setTaskCount(taskCount).build();
    return Optional.of(allocation);
}

From source file:com.github.horrorho.liquiddonkey.cloud.data.FileGroups.java

static ICloud.MBSFileAuthTokens fileIdToSignatureAuthTokens(Collection<ICloud.MBSFile> files,
        Collection<ICloud.MBSFileAuthToken> fileIdAuthTokens) {

    Map<ByteString, ByteString> fileIdToSignature = files.stream()
            .collect(Collectors.toMap(ICloud.MBSFile::getFileID, ICloud.MBSFile::getSignature));

    // Somewhat confusing proto definitions.
    // Each file is requested by file signature/ checksum not by it's FileID
    ICloud.MBSFileAuthTokens.Builder builder = ICloud.MBSFileAuthTokens.newBuilder();
    fileIdAuthTokens.stream().forEach(token -> builder.addTokens(ICloud.MBSFileAuthToken.newBuilder()
            .setFileID(fileIdToSignature.get(token.getFileID())).setAuthToken(token.getAuthToken()).build()));
    return builder.build();
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

@Override
public boolean test(String[] args) throws IllegalArgumentException {
    try {/*from ww w  . j  a v  a  2s  .co  m*/
        Map<Option, Property> optionKeyMap = optionKeyMapSupplier.get();

        Options options = new Options();
        optionKeyMap.keySet().forEach(options::addOption);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);

        Map<Property, String> properties = Stream.of(commandLine.getOptions())
                .collect(Collectors.toMap(optionKeyMap::get, this::parse));

        if (properties.containsKey(Property.ARGS_HELP)) {
            help(OptionsFactory.options().keySet());
            return false;
        }

        List<String> operands = commandLine.getArgList();
        switch (operands.size()) {
        case 0:
            // No setAuthenticationProperties credentials
            throw new IllegalArgumentException("missing appleid/ password or authentication token");
        case 1:
            // Authentication token
            properties.put(Property.AUTHENTICATION_TOKEN, operands.get(0));
            break;
        case 2:
            // AppleId/ password pair
            properties.put(Property.AUTHENTICATION_APPLEID, operands.get(0));
            properties.put(Property.AUTHENTICATION_PASSWORD, operands.get(1));
            break;
        default:
            throw new IllegalArgumentException(
                    "too many non-optional arguments, expected appleid/ password or authentication token only");
        }
        Property.setProperties(properties);
        return true;

    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getLocalizedMessage());
    }
}

From source file:com.epam.dlab.billing.azure.AzureInvoiceCalculationService.java

/**
 * Constructs service class//from w  w  w .  ja v  a2  s .  c om
 *
 * @param billingConfigurationAzure contains <code>billing-azure</code> module configuration
 * @param billableResources         resources that invoices should be calculated for
 */
public AzureInvoiceCalculationService(BillingConfigurationAzure billingConfigurationAzure,
        Set<AzureDlabBillableResource> billableResources) {
    this.billingConfigurationAzure = billingConfigurationAzure;
    this.billableResources = billableResources.stream()
            .collect(Collectors.toMap(AzureDlabBillableResource::getId, e -> e));
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.providers.aws.AmazonImageTagger.java

@Override
public ImageTagger.OperationContext getOperationContext(Stage stage) {
    StageData stageData = (StageData) stage.mapTo(StageData.class);

    Collection<MatchedImage> matchedImages = findImages(stageData.imageNames, stage);
    if (stageData.regions == null || stageData.regions.isEmpty()) {
        stageData.regions = matchedImages.stream().flatMap(matchedImage -> matchedImage.amis.keySet().stream())
                .collect(Collectors.toSet());
    }//from   w  w  w.  j  av a 2s  .c o  m

    stageData.imageNames = matchedImages.stream().map(matchedImage -> matchedImage.imageName)
            .collect(Collectors.toList());

    // Built-in tags are not updatable
    Map<String, String> tags = stageData.tags.entrySet().stream()
            .filter(entry -> !BUILT_IN_TAGS.contains(entry.getKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    List<Image> targetImages = new ArrayList<>();
    Map<String, Object> originalTags = new HashMap<>();
    List<Map<String, Map>> operations = new ArrayList<>();

    for (MatchedImage matchedImage : matchedImages) {
        Image targetImage = new Image(matchedImage.imageName, defaultBakeAccount, stageData.regions, tags);
        targetImages.add(targetImage);

        log.info(format("Tagging '%s' with '%s' (executionId: %s)", targetImage.imageName, targetImage.tags,
                stage.getExecution().getId()));

        // Update the tags on the image in the `defaultBakeAccount`
        operations.add(ImmutableMap.<String, Map>builder().put(OPERATION,
                ImmutableMap.builder().put("amiName", targetImage.imageName).put("tags", targetImage.tags)
                        .put("regions", targetImage.regions).put("credentials", targetImage.account).build())
                .build());

        // Re-share the image in all other accounts (will result in tags being updated)
        matchedImage.accounts.stream().filter(account -> !account.equalsIgnoreCase(defaultBakeAccount))
                .forEach(account -> {
                    stageData.regions
                            .forEach(region -> operations.add(ImmutableMap.<String, Map>builder()
                                    .put(ALLOW_LAUNCH_OPERATION, ImmutableMap.builder().put("account", account)
                                            .put("credentials", defaultBakeAccount).put("region", region)
                                            .put("amiName", targetImage.imageName).build())
                                    .build()));
                });

        originalTags.put(matchedImage.imageName, matchedImage.tagsByImageId);
    }

    Map<String, Object> extraOutput = objectMapper.convertValue(stageData, Map.class);
    extraOutput.put("targets", targetImages);
    extraOutput.put("originalTags", originalTags);
    return new ImageTagger.OperationContext(operations, extraOutput);
}

From source file:com.nirmata.workflow.details.TestJsonSerializer.java

@Test
public void testRunnableTask() {
    Map<TaskId, ExecutableTask> tasks = Stream.generate(() -> "").limit(random.nextInt(3) + 1)
            .collect(Collectors.toMap(s -> new TaskId(), s -> new ExecutableTask(new RunId(), new TaskId(),
                    randomTaskType(), randomMap(), random.nextBoolean())));
    List<RunnableTaskDag> taskDags = Stream.generate(() -> new RunnableTaskDag(new TaskId(), randomTasks()))
            .limit(random.nextInt(3) + 1).collect(Collectors.toList());
    LocalDateTime completionTime = random.nextBoolean() ? LocalDateTime.now() : null;
    RunId parentRunId = random.nextBoolean() ? new RunId() : null;
    RunnableTask runnableTask = new RunnableTask(tasks, taskDags, LocalDateTime.now(), completionTime,
            parentRunId);/*from   w  w  w  . j  av  a2  s.  c  om*/
    JsonNode node = newRunnableTask(runnableTask);
    String str = nodeToString(node);
    System.out.println(str);

    RunnableTask unRunnableTask = getRunnableTask(fromString(str));
    Assert.assertEquals(runnableTask, unRunnableTask);
}

From source file:io.gravitee.gateway.services.sync.SyncManager.java

public void refresh() {
    logger.debug("Refreshing gateway state...");

    try {/*ww w. ja v a 2s  .  c  om*/
        Set<io.gravitee.repository.management.model.Api> apis = apiRepository.findAll();

        // Determine deployed APIs store into events payload
        Set<Api> deployedApis = getDeployedApis(apis);

        Map<String, Api> apisMap = deployedApis.stream().filter(api -> api != null && hasMatchingTags(api))
                .collect(Collectors.toMap(Api::getId, api -> api));

        // Determine APIs to undeploy
        Set<String> apiToRemove = apiManager.apis().stream()
                .filter(api -> !apisMap.containsKey(api.getId()) || !hasMatchingTags(api)).map(Api::getId)
                .collect(Collectors.toSet());

        apiToRemove.forEach(apiManager::undeploy);

        // Determine APIs to update
        apisMap.keySet().stream().filter(apiId -> apiManager.get(apiId) != null).forEach(apiId -> {
            // Get local cached API
            Api deployedApi = apiManager.get(apiId);

            // Get API from store
            Api remoteApi = apisMap.get(apiId);

            if (deployedApi.getDeployedAt().before(remoteApi.getDeployedAt())) {
                apiManager.update(remoteApi);
            }
        });

        // Determine APIs to deploy
        apisMap.keySet().stream().filter(api -> apiManager.get(api) == null).forEach(api -> {
            Api newApi = apisMap.get(api);
            apiManager.deploy(newApi);
        });
    } catch (TechnicalException te) {
        logger.error("Unable to sync instance", te);
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.handler.KubernetesEventHandler.java

@Override
public void addRelationships(Map<KubernetesKind, List<KubernetesManifest>> allResources,
        Map<KubernetesManifest, List<KubernetesManifest>> relationshipMap) {
    relationshipMap.putAll(allResources.getOrDefault(EVENT, new ArrayList<>()).stream()
            .map(m -> ImmutablePair.of(m, KubernetesCacheDataConverter.getResource(m, V1Event.class)))
            .collect(Collectors.toMap(ImmutablePair::getLeft,
                    p -> Collections.singletonList(involvedManifest(p.getRight())))));
}