RxJava Operators: sorted()

October 22, 2018

sorted()

For finite Observables which emit items that implement the Comparable interface, it is possible to sort them with the help of the sorted() operator. It collects all emissions and then emit them in their sorted order:

import io.reactivex.Observable;

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

        observable.sorted()
                  .subscribe(System.out::println);
    }
}

It is possible to pass a Comparator to specify a given sorting logic:

import io.reactivex.Observable;

import java.util.Comparator;

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

        observable.sorted(Comparator.reverseOrder())
                  .subscribe(System.out::println);
    }
}

Of course since the Comparator interface is a FunctionalInterface (aka.: Single Abstract Method), it is possible to implement it via a Lambda:

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> observable = Observable.just("aaa", "aa", "a", "aaaaa", "aaaa");

        observable.sorted((x, y) -> Integer.compare(x.length(), y.length()))
                  .subscribe(System.out::println);
    }
}

This Lambda could be written in a more concise way:

import io.reactivex.Observable;

import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        Observable<String> observable = Observable.just("aaa", "aa", "a", "aaaaa", "aaaa");

        observable.sorted(Comparator.comparingInt(String::length))
                  .subscribe(System.out::println);
    }
}
András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami