[英]convert List<Object> to List<Map> with 2 keys using RxJava
I have a list of objects and I want to convert it to a list of maps that have a 2 keys. 我有一个对象列表,我想将其转换为具有2个键的地图列表。
code example 代码示例
// list of books (objects)
List<Book> books = new ArrayList<>();
books.add(new Book(1, 6));
books.add(new Book(2, 2));
books.add(new Book(3, 9));
books.add(new Book(4, 18));
List<Map<String, Object>> booksMap = Collections.emptyList();
// convert list into list of maps using regular for-loop
// map structure with 2 keys
for (Book book : books) {
Map<String, Object> map = new HashMap<>();
map.put("id", book.getId());
map.put("quantity", book.getQuantity());
booksMap.add(map);
}
So each object (book) have to be converted to a Map which hold a 2 keys. 因此,每个对象(书)都必须转换为具有2个键的Map。
My question is how to do it using RxJava 我的问题是如何使用RxJava做到这一点
So you want to subscribe to an Observable created with the fromIterable
convenience method which receives your list of books, afterwards it will emit the items one by one, then every item transformed into a Map and finally group them up in a list using the toList
operator. 因此,您想订阅一个由
fromIterable
便捷方法创建的Observable,该方法将接收您的书清单,此后它将逐一发出项目,然后将每个项目转换为Map,最后使用toList
运算符将它们分组在列表中。
Observable.fromIterable(books)
.map(new Function<Book, Map<String, Object>>() {
@Override
public Map<String, Object> apply(Book book) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", book.id);
map.put("quantity", book.quantity);
return map;
}
})
.toList()
.subscribe(new Consumer<List<Map<String, Object>>>() {
@Override
public void accept(List<Map<String, Object>> mapsList) throws Exception {
System.out.println(mapsList);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.