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, BinaryOperator<U> mergeFunction) 

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:Main.java

public static void main(String[] args) {
    Map<Employee.Gender, Long> countByGender = Employee.persons().stream().collect(
            Collectors.toMap(Employee::getGender, p -> 1L, (oldCount, newCount) -> newCount + oldCount));

    System.out.println(countByGender);
}

From source file:Main.java

public static void main(String[] args) {
    Map<Employee.Gender, String> genderToNamesMap = Employee.persons().stream()
            .collect(Collectors.toMap(Employee::getGender, Employee::getName,
                    (oldValue, newValue) -> String.join(", ", oldValue, newValue)));
    System.out.println(genderToNamesMap);
}

From source file:Main.java

public static void main(String[] args) {
    Map<Employee.Gender, Employee> highestEarnerByGender = Employee.persons().stream().collect(Collectors.toMap(
            Employee::getGender, Function.identity(),
            (oldPerson, newPerson) -> newPerson.getIncome() > oldPerson.getIncome() ? newPerson : oldPerson));
    System.out.println(highestEarnerByGender);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));
    Map<Integer, String> map = persons.stream()
            .collect(Collectors.toMap(p -> p.age, p -> p.name, (name1, name2) -> name1 + ";" + name2));

    System.out.println(map);//w ww.ja  v a 2  s  .  c  om
}

From source file:Main.java

@SafeVarargs
public static <K, V> Map<K, V> unionMap(boolean preserved, Map<K, V>... maps) {
    return Stream.of(maps).map(Map::entrySet).flatMap(Collection::stream).collect(Collectors
            .toMap(Map.Entry::getKey, Map.Entry::getValue, preserved ? preserveMerger() : abandonMerger()));
}

From source file:com.thinkbiganalytics.config.rest.controller.ConfigurationController.java

/**
 * Get the configuration information/*w  ww .j a  v a  2  s .co  m*/
 *
 * @return A map of name value key pairs
 */
@GET
@Path("/properties")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Gets the current Kylo configuration.")
@ApiResponses({
        @ApiResponse(code = 200, message = "Returns the configuration parameters.", response = Map.class) })
public Response getConfiguration() {
    final Map<String, Object> properties;

    if ((request.getRemoteAddr().equals("127.0.0.1") || request.getRemoteAddr().equals("0:0:0:0:0:0:0:1"))
            && env instanceof AbstractEnvironment) {
        properties = StreamSupport.stream(((AbstractEnvironment) env).getPropertySources().spliterator(), false)
                .filter(source -> source instanceof PropertiesPropertySource)
                .flatMap(source -> ((PropertiesPropertySource) source).getSource().entrySet().stream())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (value1, value2) -> value1));
    } else {
        properties = Collections.emptyMap();
    }

    return Response.ok(properties).build();
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> makeMap(String root) throws Exception {
    Path start = FileSystems.getDefault().getPath(root);
    File dir = start.toFile();/*from  www  . jav a  2s  .  c  o  m*/
    if (dir.exists() == false || dir.isDirectory() == false) {
        System.err.printf("%s doesn't exists or doesn't dir %n", root);
        System.err.println("run gradle task below");
        System.err.println("gradlew getSrcs");
        System.exit(1);
    }

    return Files.walk(start).map(Path::toFile).filter(File::isFile).filter(f -> f.getName().endsWith(".hpp"))
            .map(File::toPath).parallel().filter(OptionAnalyzer::contains).map(OptionAnalyzer::parse)
            .map(Map::entrySet).flatMap(Collection::stream)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, OptionAnalyzer::merge));
}

From source file:com.adobe.acs.commons.data.Spreadsheet.java

/**
 * Parse out the input file synchronously for easier unit test validation
 *
 * @return List of files that will be imported, including any renditions
 * @throws IOException if the file couldn't be read
 *//*from  w ww  .  ja  va2 s  . com*/
private void parseInputFile(InputStream file) throws IOException {

    XSSFWorkbook workbook = new XSSFWorkbook(file);

    final XSSFSheet sheet = workbook.getSheetAt(0);
    rowCount = sheet.getLastRowNum();
    final Iterator<Row> rows = sheet.rowIterator();

    Row firstRow = rows.next();
    headerRow = readRow(firstRow).stream().map(Variant::toString).map(this::convertHeaderName)
            .collect(Collectors.toList());
    headerTypes = readRow(firstRow).stream().map(Variant::toString)
            .collect(Collectors.toMap(this::convertHeaderName, this::detectTypeFromName, this::upgradeToArray));

    Iterable<Row> remainingRows = () -> rows;
    dataRows = StreamSupport.stream(remainingRows.spliterator(), false).map(this::buildRow)
            .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}

From source file:com.netflix.spinnaker.clouddriver.google.controllers.GoogleNamedImageLookupController.java

@VisibleForTesting
public static Map<String, String> buildTagsMap(Image image) {
    Map<String, String> tags = new HashMap<>();

    String description = image.getDescription();
    // For a description of the form:
    // key1: value1, key2: value2, key3: value3
    // we'll build a map associating each key with
    // its associated value
    if (description != null) {
        tags = Arrays.stream(description.split(",")).filter(token -> token.contains(": "))
                .map(token -> token.split(": ", 2))
                .collect(Collectors.toMap(token -> token[0].trim(), token -> token[1].trim(), (a, b) -> b));
    }//from  ww  w  . jav  a2s  .  c  o m

    Map<String, String> labels = image.getLabels();
    if (labels != null) {
        tags.putAll(labels);
    }

    return tags;
}

From source file:com.thinkbiganalytics.auth.jaas.config.JaasAuthConfig.java

@Bean(name = "jaasConfiguration")
public javax.security.auth.login.Configuration jaasConfiguration(
        Optional<List<LoginConfiguration>> loginModuleEntries) {
    // Generally the entries will be null only in situations like unit/integration tests.
    if (loginModuleEntries.isPresent()) {
        List<LoginConfiguration> sorted = new ArrayList<>(loginModuleEntries.get());
        sorted.sort(new AnnotationAwareOrderComparator());

        Map<String, AppConfigurationEntry[]> merged = sorted.stream()
                .map(c -> c.getAllApplicationEntries().entrySet()).flatMap(s -> s.stream())
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), ArrayUtils::addAll));
        return new InMemoryConfiguration(merged);
    } else {/*w  ww. j ava2  s.  c  o m*/
        return new InMemoryConfiguration(Collections.emptyMap());
    }
}