Java Reference
In-Depth Information
The first two versions of the toMap() method create the Map object for you. The third version lets you pass a
Supplier to provide a Map object yourself. I will not cover an example of using this version of the toMap() method.
Armed with two examples of collecting the data in maps, can you think of the logic for collecting data in a map
that summarizes the number of people by gender? Here is how you accomplish this:
Map<Person.Gender, Long> countByGender = Person.persons()
.stream()
.collect(Collectors.toMap(Person::getGender, p -> 1L,
(oldCount, newCount) -> oldCount++));
System.out.println(countByGender);
{MALE=4, FEMALE=2}
The key mapper function remains the same. The value mapper function is p -> 1L , which means when a person
belonging to a gender is encountered the first time, its value is set to 1. In case of a duplicate key, the merge function is
called that simply increments the old value by 1.
The last example in this category that collects the highest earner by gender in a Map is shown in Listing 13-9.
Listing 13-9. Collecting the Highest Earner by Gender in a Map
// CollectIntoMapTest.java
package com.jdojo.streams;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CollectIntoMapTest {
public static void main(String[] args) {
Map<Person.Gender, Person> highestEarnerByGender =
Person.persons()
.stream()
.collect(Collectors.toMap(Person::getGender, Function.identity(),
(oldPerson, newPerson) ->
newPerson.getIncome() > oldPerson.getIncome()?newPerson:oldPerson));
System.out.println(highestEarnerByGender);
}
}
{FEMALE=(3, Donna, FEMALE, 1962-07-29, 8700.00), MALE=(2, Jeff, MALE, 1970-07-15, 7100.00)}
The program stores the Person object as the value in the map. Note the use of Function.identity() as the
function to map values. This method returns an identity function that simply returns the value that was passed to it.
You could have used a lambda expression of person -> person in its place. The merge function compares the income
of the person already stored as the value for a key. If the new person has more income than the existing one, it returns
the new person.
Collecting data into a map is a very powerful way of summarizing data. You will see maps again when I discuss
grouping and partitioning of data shortly.
Search WWH ::




Custom Search