I'm struggling with transforming a List into a Map of Maps with RxJava. I don't know how to do the grouping based on nested value Town. I tried the following but this returns a Observable<Map<String, GroupedObservable<String, A>>>
. So how can i transform the following code so that it returns a Observable<Map<String, Map<String, Address>>
instead?
public class A{
String name;
Address address;
public A(String name, Address address) {
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public String getName() {
return name;
}
}
public class Address{
String city;
public Address(String city) {
this.city = city;
}
public String getCity() {
return city;
}
}
public void mapFunction(){
List<A> as = new ArrayList<>();
as.add(new A("foo", new Address("city1")));
as.add(new A("foo", new Address("city2")));
Observable<Map<String, GroupedObservable<String, A>>> map = Observable.fromCallable(() -> as)
.flatMapIterable(i -> i).
groupBy(A::getName, a -> a)
.toMap(a -> a.getKey());
}
You can use this method.
public static Map<String, Map<String, Address>> toMap(List<A> list) {
Map<String, Map<String, Address>> outerMap = new HashMap<>();
for (A a : list) {
String name = a.getName();
Map<String, Address> innerMap = outerMap.get(name);
if (innerMap == null) {
innerMap = new HashMap<String, Address>();
outerMap.put(name, innerMap);
}
Address address = a.getAddress();
innerMap.put(address.getCity(), address);
}
return outerMap;
}
Then wrap the result in an Observable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.