Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a POJO to a <K,V> map [duplicate]

Tags:

java

map

pojo

Possible Duplicate:
How to convert a Java object (bean) to key-value pairs (and vice versa)?

What is the best way to convert a List<POJO> to a List<Map<K,V>>. Is there a custom method/ API?

K = field name of the POJO and V is the corresponding value

public class POJO implements Serializable{

String name;
String age;
//getters and setters
}
like image 505
Victor Avatar asked May 20 '11 17:05

Victor


1 Answers

Sounds like a job for the good and old Introspector.

Working example:

// Don't be lazy like this, do something about the exceptions
public static void main(String[] args) throws Exception {
    List<POJO> pojos = new ArrayList<POJO>();
    POJO p1 = new POJO();
    p1.setAge("20");
    p1.setName("Name");
    pojos.add(p1);
    POJO p2 = new POJO();
    // ...
    System.out.println(convertCollection(pojos));
}

public static List<Map<String, ?>> convertCollection(Collection collection) 
        throws Exception {
    List<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
    for (Object element : collection) {
        list.add(getValues(element));
    }
    return list;
}

public static Map<String, ?> getValues(Object o) 
        throws Exception {
    Map<String, Object> values = new HashMap<String, Object>();
    BeanInfo info = Introspector.getBeanInfo(o.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        // This will access public properties through getters
        Method getter = pd.getReadMethod();
        if (getter != null)
            values.put(pd.getName(), getter.invoke(o));
    }
    return values;
}
like image 184
Anthony Accioly Avatar answered Sep 28 '22 05:09

Anthony Accioly