DaniloDeQueiroz
DaniloDeQueiroz

Reputation: 412

Transform HashMap values using RxJava

Is there a some way, by 'way' I mean using rx operators, to transform each HashMap value (setting the hashmap key as a value field) and get into a new Hashmap or ArrList?

Observable<HashMap<String,Allergy>> observable = MyREST.getsAllergiesApi().getAllAllergiesRx();
    observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .unsubscribeOn(Schedulers.io())
            .subscribe(new Subscriber<HashMap<String, Allergy>>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG,"onCompleted");
                }

                @Override
                public void onError(Throwable e) {
                    Log.i(TAG,"onError");
                }

                @Override
                public void onNext(HashMap<String, Allergy> allergies) {

                    mView.displayAllergies(allergies);
                    Log.i(TAG,"onNeXt");
                }
            });

Upvotes: 3

Views: 2694

Answers (1)

akarnokd
akarnokd

Reputation: 69997

You can use any classical transformation inside a map or you can flatten, map and collect values.

Observable<Map<String, Allergy>> source = ...

source.map(map -> {
    HashMap<Allergy, Allergy> newMap = new HashMap<>();
    for (Allergy a : map.values()) {
        newMap.put(a, a);
    }
    return newMap;
})
.subscribe(...)

source.flatMapIterable(map -> map.values())
.toMap(v -> v)
.subscribe(...)

Upvotes: 6

Related Questions