保存在Java
问题描述:
相同的密钥不同的值我有一个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这样的其他库。
答
这里是我的“想象的解决方案”
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);
}
答
你也可以创建自己的类:
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"));
}
您正在使用的数据结构是否包含您需要的数据?这里提出的结构的实际需求是什么? – David
尝试使用'stringbuffer'将每个数据附加到'type'关键字,它的简单 – emotionlessbananas
如果列表中的所有内容都具有相同的指示符'type',它是否需要存在? – csmckelvey