0

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. User have to send RequestAttrbs and their values in request and i have to store them.

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.

Waiting for your positive reply.

2
  • 1
    Try Map<Integer,Set<Integer> where 123 is key and [12,13,14] is value Commented Aug 5, 2014 at 17:20
  • But my key and value both must be string Commented Aug 5, 2014 at 17:23

1 Answer 1

2

You can just use a normal Map<String, List<String>> type, for example:

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:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can you please explain it with example that how i will add or remove things?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.