RxJava Operators: toMap(), toMultiMap()

October 28, 2018

toMap()

The toMap() operator collects the emissions into a Map<K, T>, where the K key is derived from the supplied Lambda function:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "b", "cc", "dddd");

        myObservable.toMap(x -> x.charAt(0))
                    .subscribe(System.out::println);
    }
}

It is possible to associate an another value to the key by providing a second Lambda parameter.
For example if we want to create a map which contains the Strings as key and their length as value:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "b", "cc", "dddd");

        myObservable.toMap(x -> x, String::length)
                    .subscribe(System.out::println);
    }
}

By default, toMap() uses a HashMap, but it is possible to provide a third Lambda parameter, which changes this default implementation:

import io.reactivex.Observable;

import java.util.concurrent.ConcurrentHashMap;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "b", "cc", "dddd");

        myObservable.toMap(x -> x, String::length, ConcurrentHashMap::new)
                    .subscribe(System.out::println);
    }
}

On thing worth noting is that if there is a key collision, by default the new item will replace the previous emission in the map:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "ab", "acc", "adddd");

        myObservable.toMap(x -> x.charAt(0), x -> x)
                    .subscribe(System.out::println);
    }
}

toMultiMap()

As we have seen above, in case of a key collision, the new emission will replace the previous emission in the map.
If you want to map multiple items to a key, you can use toMultiMap():

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "ab", "acc", "adddd");

        myObservable.toMultimap(x -> x.charAt(0), x -> x)
                    .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami