1

我正在使用queryForList从我的数据库中获取一个表,这给了我List<Map<String, Object>>. 我想使用我选择的两列将其转换为Map<String, Integer>.

目前我正在这样做

List<Map<String, Object>> customers = jdbc.queryForList("SELECT id, name FROM customers");

Map<String, Integer> customerMap = new HashMap<String, Integer>();

for (Map<String, Object> each : customers)
{
    String name = ((String)each.get("name")).trim();
    Integer id = Integer.valueOf(((BigDecimal)each.get("id")).intValue());

    customerMap.put(name, id);
}

并想知道是否有更好的方法。谢谢

4

3 回答 3

2

这为时已晚,但只是通过搜索偶然发现这一点,发现也许可以分享我的代码:

   private Map<String, Integer> convertMap(List<Map<String, Object>> input) {
        logger.trace("convertMap");
        Map<String, Integer> dest = new HashMap<>();
        for (Map<String, Object> next : input) {
            for (Map.Entry<String, Object> entry : next.entrySet()) {
                dest.put(entry.getKey(), (Integer) entry.getValue());
            }
        }
        return dest;
    }
于 2015-08-28T15:08:55.790 回答
1

你在这一行有一个不必要的拳击:

Integer id = Integer.valueOf(((BigDecimal)each.get("id")).intValue());

您应该将其替换为:

Integer id = ((BigDecimal) each.get("id")).intValue();
于 2012-12-07T11:58:46.733 回答
0

据我所知,没有其他方法可以做到这一点。通常我只会将该代码封装在一些实体静态方法中,该方法会将映射器转换为所需的对象,例如:

public class Person{
    //  define atributes, constructor, etc

    public static Iterable<Person> ExtractFromMap(List<Map<String, Object>> dataList){
        //  iterate over the List like the example you gave
        //  try to be efficient with your casts and conversions

        LinkedList<Person> ret = new LinkedList<Person>();
        for (Map<String, Object> data : dataList)
        {
            //  using the constructor
            //  or put the code directly here
            ret.add(new Person(data));
        }
        return ret;
    }

    //  you can also create a constructor that receives a Map<String, Object> to
    //  use in the static method
    private Person(Map<String, Object> data){
        //  extract and instantiate your attributes

        this.name = ((String)each.get("name")).trim();
        //  ...
    }
}

如果你愿意,你可以尝试创建一个使用反射的通用方法,但为了简单起见,我认为这个例子可以给你一个好主意。

于 2012-12-07T12:20:51.063 回答