RxJava Operators: toList(), toSortedList()

October 26, 2018

toList()

Certain operators can be used to collect all emissions into a collection.
Such operator is the toList() operator. By default the toList() operator will use the ArrayList implementation.

import io.reactivex.Observable;

public class Main {

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

        myObservable.toList()
                    .subscribe(System.out::println);
    }
}

It is possible to specify the initial size of the ArrayList, this is useful if you have at least a rough idea what number of items to expect:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.range(1, 1000);

        myObservable.toList(1000)
                    .subscribe(System.out::println);
    }
}

It is also possible to use other implementations of the List interface by passing a Lambda:

import io.reactivex.Observable;

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.range(1, 1000);

        myObservable.toList(LinkedList::new)
                    .subscribe(System.out::println);
    }
}

toSortedList()

As the name suggests, with the help of the toSortedList() operator, it is possible to collect the emissions into a sorted list, based on the Comparator implementation of the items:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.just(5, 2, 1, 6, 2, 3, 7, 4);

        myObservable.toSortedList()
                    .subscribe(System.out::println);
    }
}

Just like with the sorted() operator, it is possible to pass a Comperator parameter to apply a different sorting logic. It is also possible to pass a initial capacity for the underlying ArrayList, similarly to the toList() operator.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami