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.karus.danktitles.commands.HelpSubcommand.java

@Override
public void execute(CommandSender sender, String[] args) {

    // Methods inheritied from CommandChecker
    if (!checkLength(sender, args, 1, 3))
        return;/*from   ww  w  .jav a 2  s  . c o m*/
    if (!checkSender(sender, "danktitles.help"))
        return;

    LinkedHashMap<String, MutablePair<String, String>> parsedCommands;

    // Checks if the list needs to be filtered
    if (args.length == 1 || args[1].equals("all")) {
        parsedCommands = new LinkedHashMap<>(
                commands.entrySet().stream().filter(entry -> sender.hasPermission(entry.getValue().getLeft()))
                        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    } else {
        parsedCommands = new LinkedHashMap<>(commands.entrySet().stream().filter(
                entry -> entry.getKey().contains(args[1]) && sender.hasPermission(entry.getValue().getLeft()))
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())));
    }

    if (parsedCommands.isEmpty()) {
        sender.sendMessage(ChatColor.RED + "No matches found.");
        return;
    }

    if (args.length == 3) {
        try {
            page = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            sender.sendMessage(ChatColor.RED + "Invalid page number!");
            return;
        }
    } else {
        page = 1;
    }

    int totalPages = (int) Math.max(1, Math.floor(parsedCommands.size() / SIZE));

    if (page <= 0 || page > totalPages) {
        sender.sendMessage(ChatColor.RED + "Invalid page number!");
        return;
    }

    sender.sendMessage(ChatColor.GOLD + "[Commands - (" + ChatColor.RED + page + "/" + totalPages
            + ChatColor.GOLD + ") ]");

    ArrayList<String> keys = new ArrayList<>(parsedCommands.keySet());

    IntStream.range(page * SIZE - SIZE, parsedCommands.size()).limit(SIZE)
            .forEach(i -> sender.sendMessage(ChatColor.GOLD + commands.get(keys.get(i)).getRight()));

}

From source file:de.tudarmstadt.ukp.dkpro.core.mallet.internal.wordembeddings.MalletEmbeddingsUtils.java

/**
 * Read embeddings in text format from an InputStream.
 * Each line is expected to have a whitespace-separated list {@code <token> <value1> <value2> ...}.
 *
 * @param inputStream an {@link InputStream}
 * @param hasHeader   if true, read size and dimensionality from the first line
 * @return a {@code Map<String, double[]>} mapping each token to a vector.
 * @throws IOException if the input file cannot be read
 *///from  w  w w . j a v  a2s .  co m
public static Map<String, double[]> readEmbeddingFileTxt(InputStream inputStream, boolean hasHeader)
        throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    final int dimensions;
    final int size;

    if (hasHeader) {
        String[] header = reader.readLine().split(" ");
        assert header.length == 2;
        size = Integer.parseInt(header[0]);
        dimensions = Integer.parseInt(header[1]);
    } else {
        dimensions = -1;
        size = -1;
    }

    Map<String, double[]> embeddings = reader.lines().map(MalletEmbeddingsUtils::lineToEmbedding)
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    reader.close();

    /* assert size and dimension */
    if (hasHeader) {
        /* check that size read matches header information */
        LOG.debug("Checking number and vector sizes for all embeddings.");
        assert size == embeddings.size();
        assert embeddings.values().stream().allMatch(vector -> dimensions == vector.length);
    } else {
        LOG.debug("Checking vector sizes for all embeddings.");
        int firstLength = embeddings.values().stream().findAny().get().length;
        assert embeddings.values().stream().allMatch(vector -> firstLength == vector.length);
    }

    return embeddings;
}

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

@Override
public void export(Explorer<?> explorer, File destinationFile) {

    ObjectMapper jsonMapper = getObjectMapper();

    try {//w w  w . ja v a  2s .  com

        List<String> variableNames = explorer.all().findFirst().map(propertyVerification -> propertyVerification
                .getVariables().entrySet().stream().map(Map.Entry::getKey).sorted()).get().collect(toList());

        List<Values> variableValues = explorer.all().map(
                propertyVerifications -> new Values(propertyVerifications.getVariables().entrySet().stream()
                        .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()))))
                .collect(Collectors.toList());

        StandardResult variables = new StandardResult(buildDefinitions(variableNames, string -> ""),
                variableValues);

        PropertyVerifications<?> verifications = explorer.all().findAny()
                .orElseThrow(IllegalArgumentException::new);
        List<Definition> propertyDefinitions = buildDefinitions(
                verifications.getResults().stream().map(PropertyVerification::getName).collect(toList()),
                name -> verifications.getResults().stream()
                        .filter(verification -> verification.getName().equals(name))
                        .map(verification -> verification.getProperty().map(Property::getExplanation)
                                .orElse(""))
                        .findAny().orElse(""));

        List<Values> propertiesValues = explorer.all()
                .map(propertyVerifications -> toValues(propertyVerifications)).collect(toList());

        StandardResult properties = new StandardResult(propertyDefinitions, propertiesValues);

        Optional<Stats> statsTemplate = explorer.getStats().stream().findAny();
        List<Definition> descriptorDefinitions = buildDefinitions(
                statsTemplate.map(Stats::getDescriptorNames).orElse(Collections.emptyList()),
                name -> statsTemplate.map(stats -> stats.getDescriptorExplanation(name)).orElse(""));

        List<Values> descriptorValues = explorer.getStats().stream().map(stats -> toDescriptorValues(stats))
                .collect(Collectors.toList());

        StandardResult descriptors = new StandardResult(descriptorDefinitions, descriptorValues);

        List<StatDefinition> statsDefinitions = buildStatDefinitions(explorer.getStats(),
                name -> statsTemplate.map(stats -> stats.getStatsExplanation(name)).orElse(""));

        List<Values> statsValues = explorer.getStats().stream().map(stats -> toStatsValues(stats))
                .collect(Collectors.toList());

        StatsResult statsDefinition = new StatsResult(statsDefinitions, statsValues);

        ScoreResult scoreResult = explorer.getScore();

        ExplorerResult result = new ExplorerResult(explorer.getMetadata(), variables, statsDefinition,
                descriptors, properties, scoreResult);

        jsonMapper.writeValue(destinationFile, result);

    } catch (IOException ioe) {
        throw new IllegalStateException(
                format("Could not write explorer file at %s", destinationFile.getAbsolutePath()), ioe);
    }

}

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.//from w  ww  . j  a v  a2  s. com
 *
 * @param interestedCourseIdSet
 * @param periodsInfo
 * @return SetDomain for the 6 study periods
 */
public Map<Integer, SetDomain> createScheduleSetDomainsFor(Set<Integer> interestedCourseIdSet,
        Set<CourseSchedule> periodsInfo) {

    return getStartPeriodAndIdSetMapping(periodsInfo).entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
                Set<Integer> planedCourseIdSet = entry.getValue();

                planedCourseIdSet.retainAll(interestedCourseIdSet);//get intersection

                return planedCourseIdSet.isEmpty() ? SetDomain.emptyDomain
                        : DomainBuilder.createDomain(planedCourseIdSet);
            }));
}

From source file:com.github.horrorho.inflatabledonkey.chunk.engine.ChunkEngine.java

default Map<ChunkServer.ChunkReference, Chunk> fetch(HttpClient httpClient,
        Set<StorageHostChunkListContainer> storageHostChunkListContainerList,
        Function<ChunkServer.ChunkReference, Optional<byte[]>> getKeyEncryptionKey) {

    return storageHostChunkListContainerList.stream()
            .map(storageHostChunkList -> fetch(httpClient, storageHostChunkList, getKeyEncryptionKey))
            .map(Map::entrySet).flatMap(Collection::stream)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}

From source file:com.create.batch.TicketReaderFactory.java

public ItemStreamReader<Ticket> createReader(final Resource source) {

    final FlatFileItemReader<Ticket> reader = new FlatFileItemReader<>();
    reader.setResource(source);/*from   w  w  w. j a va 2s.  c o  m*/
    final DefaultLineMapper<Ticket> lineMapper = new DefaultLineMapper<>();
    final DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
    lineTokenizer.setNames(TICKET_FILE_CSV_FIELDS);
    lineMapper.setLineTokenizer(lineTokenizer);
    final BeanWrapperFieldSetMapper<Ticket> fieldMapper = new BeanWrapperFieldSetMapper<>();
    fieldMapper.setTargetType(Ticket.class);
    final DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    final Map<Class, PropertyEditor> customEditors = Stream
            .of(new AbstractMap.SimpleEntry<>(Date.class, new CustomDateEditor(df, false)))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    fieldMapper.setCustomEditors(customEditors);
    lineMapper.setFieldSetMapper(fieldMapper);
    reader.setLineMapper(lineMapper);
    return reader;
}

From source file:nu.yona.server.goals.service.ActivityCategoryDto.java

private static Map<Locale, String> mapToLocaleMap(Map<String, String> localeStringMap) {
    return localeStringMap.entrySet().stream()
            .collect(Collectors.toMap(e -> Locale.forLanguageTag(e.getKey()), Map.Entry::getValue));
}

From source file:org.obiba.mica.variable.search.EsPublishedDatasetVariableService.java

public Map<String, Long> getCountByStudyIds(List<String> studyIds) {
    Searcher.DocumentResults results = executeCountQuery(buildStudiesFilteredQuery(studyIds));
    if (results == null)
        return studyIds.stream().collect(Collectors.toMap(s -> s, s -> 0L));

    Map<String, Long> aggs = results.getAggregation(STUDY_ID_FIELD);
    return studyIds.stream().collect(Collectors.toMap(s -> s, s -> aggs.getOrDefault(s, 0L)));
}

From source file:me.bramhaag.discordselfbot.commands.admin.CommandEvaluate.java

@Command(name = "evaluate", aliases = { "eval", "e" }, minArgs = 1)
public void execute(@NonNull Message message, @NonNull TextChannel channel, @NonNull String[] args) {

    String input = Util.combineArgs(Arrays.copyOfRange(args, 1, args.length));
    Evaluate.Language language = Evaluate.Language.getLanguage(args[0]);

    if (language == null) {
        language = Evaluate.Language.JAVASCRIPT;
        input = Util.combineArgs(args);
    }/*from   w  w  w . ja  va2 s  .c  om*/

    input = input.startsWith("```") && input.endsWith("```") ? input.substring(3, input.length() - 3) : input;

    Evaluate.Result result = language.evaluate(Collections.unmodifiableMap(Stream
            .of(ent("jda", message.getJDA()), ent("channel", message.getChannel()),
                    ent("guild", message.getGuild()), ent("msg", message), ent("user", message.getAuthor()),
                    ent("member", message.getGuild().getMember(message.getAuthor())),
                    ent("bot", message.getJDA().getSelfUser()))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue))),
            input);

    message.editMessage(new EmbedBuilder()
            .setTitle("Evaluate " + StringUtils.capitalize(language.name().toLowerCase()), null)
            .addField("Input",
                    new MessageBuilder().appendCodeBlock(input, language.name().toLowerCase()).build()
                            .getRawContent(),
                    true)
            .addField("Output",
                    new MessageBuilder().appendCodeBlock(result.getOutput(), "javascript").build()
                            .getRawContent(),
                    true)
            .setFooter(result.getStopwatch().elapsed(TimeUnit.NANOSECONDS) == 0
                    ? Constants.CROSS_EMOTE + " An error occurred"
                    : String.format(Constants.CHECK_EMOTE + " Took %d ms (%d ns) to complete | %s",
                            result.getStopwatch().elapsed(TimeUnit.MILLISECONDS),
                            result.getStopwatch().elapsed(TimeUnit.NANOSECONDS), Util.generateTimestamp()),
                    null)
            .setColor(color).build()).queue();
}

From source file:org.openlmis.fulfillment.web.BaseController.java

Map<String, String> getErrors(BindingResult bindingResult) {
    return bindingResult.getFieldErrors().stream()
            .collect(Collectors.toMap(FieldError::getField, FieldError::getCode));
}