1

I know how to transform Map<X, Y> to Map<X, Z> using stream and it there was also a previous question about this.

But I want to learn how do it using RxJava.

And to be more specific:

//Input: 
Map<String,String> in; // map from key to a string number, for example: "10"

//transform: in -> out

//Output:
Map<String,Integer> out; //map from the same key to Integer.parseInt(val) (invariant: val is a string number)
Community
  • 1
  • 1
Gal Dreiman
  • 3,969
  • 2
  • 21
  • 40
  • Why do you want to do this with RxJava? If you have all data already available, any traditional method should work. – akarnokd Jun 30 '16 at 14:45
  • I'm trying to learn how to use RxJava, and I encountered this problem and wondered if it is possible to solve it using RxJava. – Gal Dreiman Jun 30 '16 at 14:49

2 Answers2

2

I think Dávid Karnok is right in a sense that it is not particularly useful case for RxJava if your only goal is to convert a single map. It might make more sense if you have Observable of (multiple) maps.

Then I would recommend to use a convenience of Guava transformers: https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Maps.html#transformValues(java.util.Map,%20com.google.common.base.Function)

Map<String,String> source1 = ...
Map<String,String> source2 = ...

Observable.just(source1, source2)
    .map(map->Maps.transformValues(map, v->Integer.parseInt(v)));

One nice thing about Guava's map value transformer is that it does not recreate map data structure, but instead creates a transformed view which maps values lazily (on the fly).

If you do not want to depend on Guava, you can just trivially implement Func1<Map<String,String>,Map<String,Integer>> yourself.

yurgis
  • 4,017
  • 1
  • 13
  • 22
1

You can use Observable.toMap.

I think this is a minimal example:

Map<String, String> test = new HashMap<String, String>() {

    {
        put("1", "1");
        put("2", "2");
    }
};
Map<String, Integer> res = Observable.from(test.entrySet()).toMap(e -> e.getKey(), e -> Integer.parseInt(e.getValue())).toBlocking().first();
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88