如何将Map转换为对象的ArrayList?

4
假设我收到了这样的JSON响应:
{
  "status": true,
  "data": {
    "29": "Hardik sheth",
    "30": "Kavit Gosvami"
  }
}

我正在使用Retrofit来解析Json响应。根据这个答案,我将不得不使用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>的最佳方法?

你也有动态键吗? - Vivek Mishra
@VivekMishra 是的 - Rajesh Jadav
2
为什么你一开始就需要一个列表呢?使用映射(map)作为数据的容器会更好。不过,如果你真的需要一个列表,只需通过简单的循环遍历映射,并创建PojoObject对象添加到列表中,问题出在哪里呢? - xander
5个回答

15
如果您可以扩展您的类,并编写一个带有这些值的构造函数:
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。


我们能否像通用函数一样重复使用这个流? - jebin hector
@jebinhector 你具体指的是什么?结果是一个列表,如果你指的是临时流,那么不,你不能重复使用流。 - Adowrath

0

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

 //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());
    }

请注意,使用Map.Entry无法更改键的值,这使得OP的动态键不可能。 - Adowrath

-2

试试这个

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();

如果它是一个 Map<Key, PojoObject>,那么这个方法可以工作。但是,如果它是一个 Map<String, String>,正如 OP 所述,它将创建一个 ArrayList<String> - Adowrath
2
这是错误的。map.values()将返回一个仅包含值的List<String>:"Hardik sheth","Kavit Gosvami"。 - Conffusion
编辑没有解决问题,你仍然没有PojoObjects。 - Adowrath

-3
你可以使用这个方法将映射(map)转换为列表(list)。
List<PojoObject> list = new ArrayList<PojoObject>(map.values());

假设:

Map <Key,Value> map;

1
如果它是一个 Map<Key, PojoObject>,那么这个方法可以工作。但是,如果它是一个 Map<String, String>,正如 OP 所述,它将创建一个 ArrayList<String> - Adowrath
这将无法工作,因为它无法解析构造函数 'ArrayList(java.util.Collection<java.lang.String>)'。 - Rajesh Jadav

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

这可能是最好的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接