4

Suppose I have having Json response like this:

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

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;
    }
}

What is the best way to convert a Map<key,value> to a List<PojoObject>?

Community
  • 1
  • 1
Rajesh Jadav
  • 12,801
  • 5
  • 53
  • 78

5 Answers5

15

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

If you can't:

map.entrySet()
   .stream()
   .map(e -> {
       PojoObject po = new PojoObject();
       po.setMapKey(e.getKey());
       po.setMapValue(e.getValue());
       return po;
 }).collect(Collectors.toList());

Note that this uses Java 8 Stream API.

Adowrath
  • 701
  • 11
  • 24
0

Looks like Java has exact POJO Map.Entry like you want. Hence, you can extract the entry set from map and iterate over the entry set like below or you can further convert the set to list like in next snippet and continue with your processing.

 //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());
    }
ininprsr
  • 2,472
  • 2
  • 14
  • 9
  • Note that it is not possible to change the key's value with `Map.Entry`, which makes OP's dynamic keys impossible. – Adowrath Mar 15 '17 at 07:44
-2

Try this

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

Or

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

Should be noted that the ordering of both arrays may not be the same.

or

hashMap.entrySet().toArray();
ND1010_
  • 3,743
  • 24
  • 41
-3

You can use this method to convert map to list

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

Assuming:

Map <Key,Value> map;
Piyush
  • 18,895
  • 5
  • 32
  • 63
Automator1992
  • 116
  • 1
  • 3
-3
ArrayList<Map<String,String>> list = new ArrayList<Map<String,String>>();

this may be the best way.

AG_
  • 54
  • 3