【问题标题】:Converting List<Map<String, Object>> to Map<String, Integer>将 List<Map<String, Object>> 转换为 Map<String, Integer>
【发布时间】:2012-12-07 11:37:31
【问题描述】:

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

目前我正在这样做

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

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

【问题讨论】:

  • 请这个link 帮助而不是Conversation 你不能使用地图。我只是猜测。

标签: java


【解决方案1】:

这已经太晚了,但只是在搜索中偶然发现,发现也许可以分享我的代码:

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

【讨论】:

    【解决方案2】:

    你在这一行有一个不必要的装箱:

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

    您应该将其替换为:

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

    【讨论】:

    • 这给了我一个拳击警告。 “int 类型的表达式被装箱成 Integer”。使用Integer.valueOf() 还是只使用@SuppressWarning 更好?
    • 您可以将其存储为 int。当您将其存储在 Map 上时,Java 编译器会自动将其转换为 Integer(无法在此处对其进行测试,但我很确定)。
    • int id = ((BigDecimal) each.get("id")).intValue(); 否则。
    【解决方案3】:

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

    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();
            //  ...
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-21
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多