我正在努力使用RxJava将列表转换成Maps。
我不知道如何基于嵌套值Town进行分组。
我尝试了以下操作,但这返回了Observable<Map<String, GroupedObservable<String, A>>>
。那么,如何转换以下代码,使其返回Observable<Map<String, Map<String, Address>>
呢?
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());
}
答案 0 :(得分:0)
您可以使用此方法。
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;
}
然后将结果包装在Observable中。