如何将映射转换为对象的数组列表? [英] How to convert a Map to Arraylist of Objects?
本文介绍了如何将映射转换为对象的数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的 Json 响应:
Suppose I have having Json response like this:
{
"status": true,
"data": {
"29": "Hardik sheth",
"30": "Kavit Gosvami"
}
}
我正在使用 Retrofit 来解析 Json 响应.根据 this 答案,我将不得不使用 Map<String, String>
将给出 Map 中的所有数据.现在我想要的是 ArrayList
.
I am using Retrofit to parse Json response. As per this answer I will have to use Map<String, String>
which will give all the data in Map. Now what I want is ArrayList<PojoObject>
.
PojoObject.class
public class PojoObject {
private String mapKey, mapValue;
public String getMapKey() {
return mapKey;
}
public void setMapKey(String mapKey) {
this.mapKey = mapKey;
}
public String getMapValue() {
return mapValue;
}
public void setMapValue(String mapValue) {
this.mapValue = mapValue;
}
}
将 Map
转换为 List
的最佳方法是什么?
What is the best way to convert a Map<key,value>
to a List<PojoObject>
?
推荐答案
如果你可以扩展你的类,让构造函数也接受这些值:
If you can expand your class to have a constructor taking the values as well:
map.entrySet()
.stream()
.map(e -> new PojoObject(e.getKey(), e.getValue()))
.collect(Collectors.toList());
如果你不能:
map.entrySet()
.stream()
.map(e -> {
PojoObject po = new PojoObject();
po.setMapKey(e.getKey());
po.setMapValue(e.getValue());
return po;
}).collect(Collectors.toList());
请注意,这里使用 Java 8 Stream
API.
Note that this uses Java 8 Stream
API.
这篇关于如何将映射转换为对象的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文