简体   繁体   English

Java8:地图 <X, Y> 到地图 <X, Z> 使用RxJava

[英]Java8: Map<X, Y> to Map<X, Z> using RxJava

I know how to transform Map<X, Y> to Map<X, Z> using stream and it there was also a previous question about this. 我知道如何使用流将Map<X, Y>Map<X, Z> ,之前还有一个关于此的问题

But I want to learn how do it using RxJava. 但我想学习如何使用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)

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. 我认为DávidKarnok在某种意义上是正确的,如果你的唯一目标是转换单个地图,那么它对RxJava来说并不是特别有用。 It might make more sense if you have Observable of (multiple) maps. 如果您有(多个)地图的Observable可能会更有意义。

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) 然后我建议使用方便的Guava变换器: https ://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Maps.html#transformValues(java.util 。地图,%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). 关于Guava的地图值变换器的一个好处是它不会重新创建地图数据结构,而是创建一个变换的视图,它可以懒惰地(动态地)映射值。

If you do not want to depend on Guava, you can just trivially implement Func1<Map<String,String>,Map<String,Integer>> yourself. 如果你不想依赖Guava,你可以自己轻松地实现Func1<Map<String,String>,Map<String,Integer>>

You can use Observable.toMap . 您可以使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM