2016-07-22 36 views
-6

相同的密鑰不同的值我有一個depoCinsiList它具有以下值:保存在Java

["D","S"] 

我想有一個結構像這樣

[{type: "D"}, {type: "S"}] 

我已經嘗試實現這通過使用Map。

List<String> typeList = typeService.getDepoCinsiList(); //list which returns ["D","S"] 

Map<String, List<String>> map = new HashMap<String, List<String>>(); 

for (int j = 0; j < typeList.size(); j++) { 
    map.put("type", typeList); 
} 

ArrayList<Map<String, List<String>>> mapList = new ArrayList<Map<String, List<String>>>(); 
mapList.add(map); 

然而,這將返回如下:

"type":["D","S"] 

哪些數據結構,我應該使用來實現列表作爲[{type: "D"}, {type: "S"}]?我可以使用JSON,但我不想使用像gson這樣的其他庫。

+0

您正在使用的數據結構是否包含您需要的數據?這裏提出的結構的實際需求是什麼? – David

+0

嘗試使用'stringbuffer'將每個數據附加到'type'關鍵字,它的簡單 – emotionlessbananas

+2

如果列表中的所有內容都具有相同的指示符'type',它是否需要存在? – csmckelvey

回答

-2

這裏是我的「想象的解決方案」

List<Map<String, String>> list = new ArrayList<Map<String, String>>(); 

for (int j = 0; j < typeList.size(); j++) { 
    Map<String, String> map = new HashMap<String, String>(); 
    map.put("type", typeList.get(j)); 
    list.add(map); 
} 
-1

你也可以創建自己的類:

public static void main(String[] args) { 
    class Typed { 
     private String type; 
     public Typed(String type){ 
      this.type= type; 
     } 
     public String getType(){ 
      return this.type; 
     } 

    } 

    List<Typed> myList = new ArrayList<>(); 
    myList.add(new Typed("D")); 
    myList.add(new Typed("S")); 

} 
1

地圖犯規允許重複鍵

我喜歡@Zeromus解決辦法,但我會去Guava's multimaps