Java:如何转换List<?>到地图< String,?> [英] Java: how to convert a List<?> to a Map<String,?>

查看:75
本文介绍了Java:如何转换List<?>到地图< String,?>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法来获取下面的对象特定例程,并将其抽象为一种方法,您可以传递类,列表和字段名以获取地图。
如果我可以得到一个一般的指针,使用的模式或等等,可以让我从正确的方向开始。

I would like to find a way to take the object specific routine below and abstract it into a method that you can pass a class, list, and fieldname to get back a Map. If I could get a general pointer on the pattern used or , etc that could get me started in the right direction.

  Map<String,Role> mapped_roles = new HashMap<String,Role>();
    List<Role> p_roles = (List<Role>) c.list();
    for (Role el :  p_roles) {
        mapped_roles.put(el.getName(), el);
    }

(伪代码)

  Map<String,?> MapMe(Class clz, Collection list, String methodName)
  Map<String,?> map = new HashMap<String,?>();
    for (clz el :  list) {
        map.put(el.methodName(), el);
    }

可以吗?

推荐答案

这是我会做的。我不完全确定我是否正在处理泛型,但是很好:

Here's what I would do. I am not entirely sure if I am handling generics right, but oh well:

public <T> Map<String, T> mapMe(Collection<T> list) {
   Map<String, T> map = new HashMap<String, T>();
   for (T el : list) {
       map.put(el.toString(), el);
   }   
   return map;
}

只需传递一个集合,并让你的类实现toString()到返回名称。多态会照顾它。

Just pass a Collection to it, and have your classes implement toString() to return the name. Polymorphism will take care of it.

这篇关于Java:如何转换List&lt;?&gt;到地图&lt; String,?&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆