Java - Stream Collecting Data into Maps

Introduction

You can collect data from a stream into a Map.

The toMap() method of the Collectors class returns a collector to collect data in a Map.

The method is overloaded and it has three versions:

toMap(Function<? super T,? extends K> keyMapper, 
      Function<? super T,? extends U> valueMapper)

toMap(Function<? super T,? extends K> keyMapper, 
      Function<? super T,? extends U> valueMapper, 
      BinaryOperator<U> mergeFunction)

toMap(Function<? super T,? extends K> keyMapper, 
      Function<? super T,? extends U> valueMapper, 
      BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

The first argument maps the stream elements to keys in the map.

The second argument maps stream elements to values in the map.

If duplicate keys are found, an IllegalStateException is thrown.

The following code collects a person's data in a Map<long,String> whose keys are the person's ids and values are person's names:

Map<Long,String> idToNameMap = 
     Person.persons()
           .stream()
           .collect(Collectors.toMap(Person::getId, Person::getName));

A merge function is passed the old and new values for the duplicate key.

The function would merge the two values and return a new value that will be used for the key.


Map<Person.Gender,String> genderToNamesMap = 
    Person.persons()
          .stream()
          .collect(Collectors.toMap(Person::getGender, 
                   Person::getName,
                   (oldValue, newValue) -> String.join(", ", oldValue, newValue)));

The first two versions of the toMap() method create the Map object.

The third version lets you pass a Supplier to provide a Map object yourself.

To collect data in a map that summarizes the number of people by gender:

Map<Person.Gender, Long> countByGender = 
    Person.persons()
          .stream()
          .collect(Collectors.toMap(Person::getGender, 
                                    p -> 1L,
                                    (oldCount, newCount) -> oldCount++));

Related Topic