My problems starts here with a limitation with HashMap in Java that does not allow using multiple values for same key. As in my code written below i need to have multiple values for k5 & k6.

map is the main hashmap of QueryParameters that i will be passing on to be used in my RestAPI request. Approach tried: Created different Map of String and String[] type and then merge which i found would not be allowed to be merged.Code of the same has been marked as commented via //

My REST request looks like the following and i am finding it difficult how to send it in the following manner:

https://myURL/api&k1[]=value&k2=2value&k5[]=v3&k5[]=v4&k5[]=v5&k6[]=v7&k6[]=v8&k6[]=v8

If there is any other way to represent this in Java, please do let me know.

Map<String, String> map = new HashMap<>();
map.put("k1", "value");
map.put("k2", "2value");
//String[] k5 = new String[]{"v3", "v4", "v5"};
map.put("k5[]", "v3");
map.put("k5[]", "v4");
map.put("k5[]", "v5");
//String[] k6= new String[]{"v7", "v8", "v9"};
map.put("k6[]", "v7");
map.put("k6[]", "v8");
map.put("k6[]", "v9");

2 Answers

4
Nicholas K On Best Solutions

It pretty simple actually. Here's what you'll need to do:

Map<String, String[]> map = new HashMap<>();
map.put("v3", new String[] { "v", "foo", "bar" });   

If you want to add more elements to this, you can define the map as Map<String, List<String>>

Map<String, List<String>> map = new HashMap<>();
List<String> initialList = new ArrayList<>();
initialList.add("v");
initialList.add("foo");
initialList.add("bar");
map.put("v3", initialList);

// add some new String      
map.get("v3").add("Some_new_string");

// adding a whole new list
map.get("v3").addAll(Arrays.asList("new_element_1", "new_element_2"));
3
steffen On

You want this map:

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

For adding and removing strings, use computeIfAbsent and computeIfPresent:

// Add str to list of strings indexed by key
strings.computeIfAbsent(key, ign -> new ArrayList<>()).add(str);

// Remove str from list of strings indexed by key
strings.computeIfPresent(key, (i, c) -> c.remove(str) && c.isEmpty() ? null : c);

This dynamically creates and removes the Lists in the map. Example:

Map<String, List<String>> strings = new HashMap<>();
put(strings, "key", "a"); // ["key" => ["a"]] <-- list dynamically created
put(strings, "key", "b"); // ["key" => ["a", "b"]]
remove(strings, "key", "b"); // ["key" => ["a"]]
remove(strings, "key", "a"); // [] <-- no leftovers