2016-07-22 31 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