将 POJO 转换为 地图

发布于 2024-11-09 06:42:21 字数 483 浏览 0 评论 0 原文

可能的重复:
如何转换Java 对象(bean)到键值对(反之亦然)?

List 转换为 Java 对象(bean)的最佳方法是什么?到列表>。 有自定义方法/ API 吗?

K = POJO 的字段名称,V 是对应的值

public class POJO implements Serializable{

String name;
String age;
//getters and setters
}

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

淤浪 2024-11-16 06:42:22

如果你指的是 K,V 的地图那么这将起作用

List<Pojo> pojos = ...;
Map<String, String> map = new HashMap<String,String>();
for (Pojo pojo : pojos) {
 map.put(pojo.getName(), pojo.getAge());
}

If you mean a map of K,V then this will work

List<Pojo> pojos = ...;
Map<String, String> map = new HashMap<String,String>();
for (Pojo pojo : pojos) {
 map.put(pojo.getName(), pojo.getAge());
}
在你怀里撒娇 2024-11-16 06:42:22

假设您想要一个没有列表的 Map ,最简单的方法可能是使用一个简单的 for 循环:

Map<K,V> theMap = new HashMap<K,V>();
for (POJO obj : theList) {
    // Obviously the below can be simplified to one line
    // but it makes sense to make everything explicit for
    // ease of reading
    K key = ... // obj.getName() maybe?
    V value = ... // obj itself maybe?
    theMap.put(key, value);
}

Assuming you want a Map sans list, the easiest way is probably with a simple for loop:

Map<K,V> theMap = new HashMap<K,V>();
for (POJO obj : theList) {
    // Obviously the below can be simplified to one line
    // but it makes sense to make everything explicit for
    // ease of reading
    K key = ... // obj.getName() maybe?
    V value = ... // obj itself maybe?
    theMap.put(key, value);
}
不喜欢何必死缠烂打 2024-11-16 06:42:22

您需要知道 POJO 名称。假设您有类似 pojo.getName() 的内容,那么它会像这样:

Map<String, Pojo> pojoMap = new HashMap<String, Pojo>();
for (Pojo pojo:pojoList) {
  pojoMap.put(pojo.getName(), pojo);
}

注意我更改了您的要求,我转换了一个一张地图的 pojo 列表。

You need to know the POJO name. Assuming you have something like pojo.getName(), then it goes like this:

Map<String, Pojo> pojoMap = new HashMap<String, Pojo>();
for (Pojo pojo:pojoList) {
  pojoMap.put(pojo.getName(), pojo);
}

Note that I changed your requirement, I've converted one list of pojos to one map.

闻呓 2024-11-16 06:42:21

听起来像是一份适合老好人的工作 Introspector

工作示例:

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

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;
}
他不在意 2024-11-16 06:42:21

Apache Commons 的 BeanMap 完成这项工作

BeanMap from Apache Commons does the job

溇涏 2024-11-16 06:42:21

您可以使用反射来做到这一点。请参阅 Class.getDeclaredFields。这将为您提供类的字段,然后您可以从中获取值并填充您的地图。

请注意,您可能需要调用 setAccessible 如果字段是私有的,然后您才能获取值。

编辑:我的答案仅适用于构建地图时不知道 POJO 的字段/实现的情况。

You can use reflection to do that. See Class.getDeclaredFields. That will give you the fields of a class, you can then get the values from them and populate your map.

Note that you might need to invoke setAccessible on the fields if the are private before you can get the value.

Edit: My answer only applies to the case where you don't know the fields / implementation of the POJO when you build the map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文