簡體   English   中英

轉換列表 <Map<String, Object> &gt;到地圖 <String, Integer>

[英]Converting List<Map<String, Object>> to Map<String, Integer>

我使用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);
}

並想知道是否有更好的方法。 謝謝

這太晚了,但只是偶然發現了搜索,發現也許可以分享我的代碼:

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

你在這一行中有一個不必要的拳擊:

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

您應該將其替換為:

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

據我所知,沒有其他辦法可以做到這一點。 通常我會將該代碼封裝在某個實體靜態方法中,該方法將映射器轉換為所需對象,如:

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

如果你願意,你可以嘗試創建一個使用反射的泛型方法,但為了保持簡單,我想這個例子可以給你一個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM