如何将地图转换为对象的Arraylist?

时间:2017-03-09 12:05:33

标签: java android arraylist

假设我有这样的Json响应:

{
  "status": true,
  "data": {
    "29": "Hardik sheth",
    "30": "Kavit Gosvami"
  }
}

我正在使用Retrofit来解析Json响应。根据{{​​3}}答案,我将不得不使用Map<String, String>来提供Map中的所有数据。现在我想要的是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<key,value>转换为List<PojoObject>的最佳方式是什么?

5 个答案:

答案 0 :(得分:3)

如果你可以扩展你的类,让构造函数也接受这些值:

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。

答案 1 :(得分:0)

看起来Java有你想要的精确POJO Map.Entry。因此,您可以从地图中提取条目集并迭代以下条目集,或者您可以进一步将该集转换为列表,如下一个代码段所示,并继续处理。

 //fetch entry set from map
Set<Entry<String, String>> set = map.entrySet();        

    for(Entry<String, String> entry: set) {
        System.out.println(entry.getKey() +"," + entry.getValue());
    }

    //convert set to list
    List<Entry<String, String>> list = new ArrayList(set);

    for(Entry<String, String> entry: list) {
        System.out.println(entry.getKey() +"," + entry.getValue());
    }

答案 2 :(得分:-1)

您可以使用此方法将地图转换为列表

List<PojoObject> list = new ArrayList<PojoObject>(map.values());

假设:

Map <Key,Value> map;

答案 3 :(得分:-1)

试试这个

List<Value> list = new ArrayList<Value>(map.values());

hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values

应该注意两个数组的排序可能不一样。

hashMap.entrySet().toArray();

答案 4 :(得分:-1)

ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>();

这可能是最好的方式。