2016-06-30 46 views
1

到地图 我知道如何使用流改造 Map<X, Y>Map<X, Z>,它也有一个 previous question这一点。
Java8:地图<X, Y>使用RxJava

但我想了解它使用RxJava怎么办。

而且更具体:

//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) 
+0

为什么要与RxJava做到这一点?如果你已经有了所有的数据,那么任何传统的方法都应该有效。 – akarnokd

+0

我想学习如何使用RxJava,并且我遇到了这个问题,并想知道是否可以使用RxJava来解决它。 –

回答

1

您可以使用Observable.toMap

我认为这是一个小例子:

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(); 
2

我认为大卫Karnok是正确的,从某种意义上说,它不是RxJava特别有用的情况下,如果你唯一的目标是转换单个地图。 如果您拥有(多个)地图的可观察性,这可能会更有意义。

然后,我会建议使用番石榴变压器的方便: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))); 

约番石榴的地图值转换的一个好处是,它不会重新映射数据结构,而是创建了一个转化图,该地图懒惰地(在飞行中)。

如果你不想依赖于番石榴,你可以平凡实现Func1<Map<String,String>,Map<String,Integer>>自己。

相关问题