[java] Collectors.toMap() keyMapper -- more succinct expression?

I'm trying to come up with a more succinct expression for the "keyMapper" function parameter in the following Collectors.toMap() call:

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(
                new Function<Person, String>() { 
                    public String apply(Person p) { return p.getLast(); } 
                },
                Function.<Person>identity()));

It seems that I should be able to inline it using a lambda expression, but I cannot come up with one that compiles. (I'm quite new to lambdas, so that's not much of a surprise.)

Thanks.

--> Update:

As noted in the accepted answer

Person::getLast

is what I was looking for, and is something I had tried. However, the BETA_8 nightly build of Eclipse 4.3 was the problem -- it flagged that as wrong. When compiled from the command-line (which I should have done before posting), it worked. So, time to file a bug with eclipse.org.

Thanks.

This question is related to java collections lambda java-8 java-stream

The answer is


You can use a lambda:

Collectors.toMap(p -> p.getLast(), Function.identity())

or, more concisely, you can use a method reference using :::

Collectors.toMap(Person::getLast, Function.identity())

and instead of Function.identity, you can simply use the equivalent lambda:

Collectors.toMap(Person::getLast, p -> p)

If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.


List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)


We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with collections tag:

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library? Lambda expression to convert array/List of String to array/List of Integers Print all key/value pairs in a Java ConcurrentHashMap UnmodifiableMap (Java Collections) vs ImmutableMap (Google) How to sort a HashSet? How to find Max Date in List<Object>? Comparing two hashmaps for equal values and same key sets? How to sort Counter by value? - python How to quickly and conveniently create a one element arraylist How to convert Set to Array? Array vs ArrayList in performance Collectors.toMap() keyMapper -- more succinct expression? How can I loop through a List<T> and grab each item? How to sort an ArrayList in Java Ways to iterate over a list in Java java.math.BigInteger cannot be cast to java.lang.Long Create a List of primitive int? How to find an object in an ArrayList by property Removing items from a list Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array)) How to use Collections.sort() in Java? How to sort an ArrayList? How to shuffle an ArrayList Best way to convert list to comma separated string in java How do I remove an array item in TypeScript? Add multiple items to already initialized arraylist in java Retrieving a List from a java.util.stream.Stream in Java 8 Magento: Set LIMIT on collection How to copy a java.util.List into another java.util.List How to remove element from ArrayList by checking its value? List(of String) or Array or ArrayList How to search in a List of Java object Is there a short contains function for lists? How to make Java Set? Best practice to validate null and empty collection in Java How to iterate through LinkedHashMap with lists as values Is there a common Java utility to break a list into batches? Java: How to convert String[] to List or Set ArrayList insertion and retrieval order How to add element in List while iterating in java? Checking if a collection is empty in Java: which is the best method?

Questions with lambda tag:

Java 8 optional: ifPresent return object orElseThrow exception How to properly apply a lambda function into a pandas data frame column What are functional interfaces used for in Java 8? Java 8 lambda get and remove element from list Variable used in lambda expression should be final or effectively final Filter values only if not null using lambda in Java8 forEach loop Java 8 for Map entry set Java 8 Lambda Stream forEach with multiple statements Java 8 stream map to list of keys sorted by values Task.Run with Parameter(s)? Modifying local variable from inside lambda Java 8 Lambda filter by Lists Java 8 lambda Void argument Passing capturing lambda as function pointer How to use a Java8 lambda to sort a stream in reverse order? Java 8 lambdas, Function.identity() or t->t Can a java lambda have more than 1 parameter? Java 8, Streams to find the duplicate elements How can I throw CHECKED exceptions from inside Java 8 streams? Java 8 stream map on entry set Does Java SE 8 have Pairs or Tuples? Proper usage of Optional.ifPresent() Java 8 Filter Array Using Lambda Java 8 Streams: multiple filters vs. complex condition Python loop for inside lambda How to map to multiple elements with Java 8 streams? Return from lambda forEach() in java Break or return from Java 8 stream forEach? Lambda expression to convert array/List of String to array/List of Integers How to check if element exists using a lambda expression? In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? Using Java 8's Optional with Stream::flatMap Java "lambda expressions not supported at this language level" Filter Java Stream to 1 and only 1 element FirstOrDefault returns NullReferenceException if no match is found Difference between final and effectively final Java 8 List<V> into Map<K, V> Java 8: Lambda-Streams, Filter by Method with Exception How do I use the new computeIfAbsent function? Collectors.toMap() keyMapper -- more succinct expression? Cannot convert lambda expression to type 'string' because it is not a delegate type python max function using 'key' and lambda expression Java 8 Lambda function that throws exception? Conditional statement in a one line lambda function in python? How to use Lambda in LINQ select statement Retrieving a List from a java.util.stream.Stream in Java 8 C# Pass Lambda Expression as Method Parameter Where do I mark a lambda expression async? What is key=lambda How do I define a method which takes a lambda as a parameter in Java 8?

Questions with java-8 tag:

Default interface methods are only supported starting with Android N Class has been compiled by a more recent version of the Java Environment Why is ZoneOffset.UTC != ZoneId.of("UTC")? Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit What are functional interfaces used for in Java 8? java.time.format.DateTimeParseException: Text could not be parsed at index 21 Java 8 lambda get and remove element from list How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Convert LocalDateTime to LocalDateTime in UTC Java 8 Stream API to find Unique Object matching a property value Difference between `Optional.orElse()` and `Optional.orElseGet()` LocalDate to java.util.Date and vice versa simplest conversion? Reverse a comparator in Java 8 Filter values only if not null using lambda in Java8 Move to next item using Java 8 foreach loop in stream What's the difference between Instant and LocalDateTime? Ignore duplicates when producing map using streams How to convert ZonedDateTime to Date? forEach loop Java 8 for Map entry set How to find distinct rows with field in list using JPA and Spring? Why should Java 8's Optional not be used in arguments Why use Optional.of over Optional.ofNullable? Java 8 Lambda Stream forEach with multiple statements Java 8 - Difference between Optional.flatMap and Optional.map Modifying Objects within stream in Java8 while iterating How can I get a List from some class properties with Java 8 Stream? How to convert an Instant to a date format? Java 8 stream map to list of keys sorted by values Moving from JDK 1.7 to JDK 1.8 on Ubuntu How to sum a list of integers with java streams? Converting Array to List Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8? Modifying local variable from inside lambda Java 8 Lambda filter by Lists JSON Java 8 LocalDateTime format in Spring Boot Java 8 lambda Void argument Error:java: javacTask: source release 8 requires target release 1.8 Registry key Error: Java version has value '1.8', but '1.7' is required Remove duplicates from a list of objects based on property in Java 8 Hashmap with Streams in Java 8 Streams to collect value of Map Get enum values as List of String in Java 8 How to execute logic on Optional if not present? How to compare LocalDate instances Java 8 org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start How to use a Java8 lambda to sort a stream in reverse order? How to decompile to java files intellij idea Group by multiple field names in java 8

Questions with java-stream tag:

Sorting a list with stream.sorted() in Java Modify property value of the objects in list using Java 8 streams How to use if-else logic in Java 8 stream forEach Java 8 lambda get and remove element from list Create list of object from another using Java 8 Streams Java 8 Stream API to find Unique Object matching a property value Reverse a comparator in Java 8 Ignore duplicates when producing map using streams Modifying Objects within stream in Java8 while iterating How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to sum a list of integers with java streams? How to use a Java8 lambda to sort a stream in reverse order? Java 8 - Best way to transform a list: map or foreach? Java 8 lambdas, Function.identity() or t->t Java 8, Streams to find the duplicate elements How can I throw CHECKED exceptions from inside Java 8 streams? What's the difference between map() and flatMap() methods in Java 8? How to check if a Java 8 Stream is empty? Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector Using Java 8 to convert a list of objects into a string obtained from the toString() method Java 8 NullPointerException in Collectors.toMap Java 8 Stream and operation on arrays Does Java SE 8 have Pairs or Tuples? Java 8 Streams: multiple filters vs. complex condition Java 8 stream reverse order Convert Iterable to Stream using Java 8 JDK Java 8 Distinct by property Find first element by predicate How to map to multiple elements with Java 8 streams? Java 8: How do I work with exception throwing methods in streams? Java 8: merge lists with stream API Java8: sum values from specific field of the objects in a list How to convert a Java 8 Stream to an Array? Fetch first element which matches criteria Java 8 method references: provide a Supplier capable of supplying a parameterized result How to add elements of a Java8 stream into an existing List In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda? Adding two Java 8 streams, or an extra element to a stream Using Java 8's Optional with Stream::flatMap Filter Java Stream to 1 and only 1 element Adding up BigDecimals using Streams Java 8 stream's .min() and .max(): why does this compile? Is it possible to cast a Stream in Java 8? Java 8 Streams FlatMap method example Custom thread pool in Java 8 parallel stream Should I always use a parallel stream when possible? Java 8 List<V> into Map<K, V> Can you split a stream into two streams? Collectors.toMap() keyMapper -- more succinct expression?