简体   繁体   English

Java中字符串数组的数组的数据结构

[英]Data structure for array of string arrays in java

I checked other questions and googled as well but didn't find a proper answer according to my demand. 我检查了其他问题,也用谷歌搜索,但没有根据我的要求找到合适的答案。

This is web app and I am using a rest service. 这是网络应用,我正在使用休息服务。 I have a class Request and it has an attribute RequestedAttrbs . 我有一个Request类,它有一个RequestedAttrbs属性。 User have to send RequestAttrbs and their values in request and i have to store them. 用户必须在请求中发送RequestAttrbs及其值,我必须存储它们。

Now user can provide: 现在用户可以提供:

id: 123
marks: 12, 13, 14

Problem is user can provide multiple attributes and can provide multiple values for each attribute. 问题在于用户可以提供多个属性,并且可以为每个属性提供多个值。 Which data structure will be best to handle this? 哪种数据结构最适合处理此问题? I am new to java and want to solve this problem. 我是Java新手,想解决这个问题。

Waiting for your positive reply. 等待您的正面答复。

You can just use a normal Map<String, List<String>> type, for example: 您可以只使用普通的Map<String, List<String>>类型,例如:

String key = "keyValue";
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";

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

if (!requestAttrbs1.containsKey(key)) {
    requestAttrbs1.put(key, new ArrayList<String>());
}
requestAttrbs1.get(key).add(value1);
requestAttrbs1.get(key).add(value2);
requestAttrbs1.get(key).add(value3);

requestAttrbs1.get(key).remove(value2);

for (String value : requestAttrbs1.get(key)) {
    System.out.println(value);
}

Alternatively, if you can use libraries you might want to look at the MultiValueMap in Commons Collections : 另外,如果可以使用库,则可能需要查看Commons Collections中的MultiValueMap

MultiValueMap<String, String> requestAttrbs2 = new MultiValueMap<String, String>();

requestAttrbs2.put(key, value1);
requestAttrbs2.put(key, value2);
requestAttrbs2.put(key, value3);

requestAttrbs2.removeMapping(key, value2);

for (String value : requestAttrbs2.getCollection(key)) {
    System.out.println(value);
}

Both code snippets will print out: 这两个代码段都将打印出来:

value1
value3

As you can see the MultiValueMap version is slightly shorter, saving you the trouble of checking whether the key already exists and explicitly getting the list out yourself. 如您所见, MultiValueMap版本略短一些,从而省去了检查密钥是否已存在并自己显式获取列表的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM