6
votes

Supposing i have the following data structure:

Map<String, ObjectA> map;

and the ObjectA:

class ObjectA {
   String a;
   String b;
   int c;    
}

My final goal is to return just:

Map<String, String>

In which the first String is the same as the original, and the second String is the 'String a'. What transformations do i need to accomplish this?

If this was a list, i would have used Observable.from(), take what i want from the single items and then at the end join them together with toList(). But this is a map and i have never nor do i know how to perform iteration over maps in RxJava. Any help would be appreciated

Edit. I know i can do this using Observable.create and use the normal Java/way of doing it like the first answer states. What i really want to know is if there are any Rx Operators that allow me to do that, like Observable.from, flatMap and toList, if i was transforming lists

2
I don't understand the question. How would you do it in plan Java?akarnokd
I would do exactly as the first comment states. But i am looking for the right RxJava Operators to do so if there are any.johnny_crq

2 Answers

17
votes

Try this code:

Observable.just(map)
        .map(stringObjectAMap -> stringObjectAMap.entrySet())
        .flatMapIterable(entries -> entries)
        .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue().a))
        .toMap(e -> e)
        .subscribe(m -> {
            //do something with map
        });
1
votes

This can also be done using java8 streams:

import java.util.HashMap;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

public class Example {
    public void method() {
        Map<String, Object> map = new HashMap<String, Object>() {{
            put("a", 4);
            put("b", new Object());
            put("c", 'o');
        }};

        Map<String, String> stringMap = map.entrySet()
                .stream()
                .collect(toMap(Map.Entry::getKey, entry -> entry.getValue().toString()));
    }
}