2012-12-07 136 views
0

我正在使用queryForList從我的數據庫中獲取一個表,它給了我List<Map<String, Object>>。我想使用我選擇的兩列將其轉換爲Map<String, Integer>將列表<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); 
} 

,並想知道是否有更好的方法。由於

+0

可能這個[鏈接](http://stackoverflow.com/questions/6917906/return -type-for-jdbctemplate-queryforlistsql-object-classtype)幫助,而不是使用地圖。我只是猜測。 – vels4j

回答

1

你在這行不必要的拳擊:

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

你應該改爲:

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

這給了我一個拳擊警告。 「int類型的表達式被整理成整數」。使用'Integer.valueOf()'還是使用'@ SuppressWarning'更好? –

+0

您可以將它作爲int存儲。當你將它存儲在Map上時,Java編譯器會自動將它轉換爲Integer(不能在這裏測試,但我非常確定)。 –

+0

'int id =((BigDecimal)each.get(「id」))。intValue();否則。 – Mik378

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

如果你願意,你可以嘗試創建,將使用一個通用的方法反思,但爲了保持簡單,我認爲這個例子可以給你一個好主意。

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; 
    } 
相關問題