I want to add an Arraylist<String> object(inputArrListObj) into my already existing Map<String, String> (param) which has some input values to be sent.
Map<String,String> param = new HashMap<String, String>();
List<String> obj = inputArrListObj;
param.put("1","Value");
//param.put("2",<Input list values>);
What should be the ideal approach to do the same?
It is not possible with your current declaration.
You must consider changing your map declaration to
Map<String,List<String>> param = new HashMap<String, List<String>>();
That allows you to insert a List as value.
However for the first case (param.put("1","Value");), your List will have only one String in it.
It's look like you want to store in your map abstract named values. If so try to use Map<String, Object> and cast to specific class when you get values from map.
Map<String, Object> param = new HashMap<String, Object>();
List<String> obj = inputArrListObj;
param.put("1", "Value");
param.put("2", obj);
...
List<String> param2 = (List<String>) param.get("2");
Related
Im storing 2 map with different structure in single map like below,
Map<String, List<String>> colMap = new HashMap<String, List<String>>();
Map<String, String> appMap = new HashMap<String, String>();
// colMap assigning some values
// appMap assigning some values
Map<String, Map> mainMap = new HashMap<String, Map>();
mainMap.put("appMap", appMap);
mainMap.put("colMap", colMap);
I want to get map one by one and iterate the map.
If I try get map like below, getting error,
.......
Map colMap = map.get("colMap");
for(Entry<String, List<String>> entry : colMap.entrySet())
Error: Type mismatch: cannot convert from element type Object to Map.Entry<String,List<String>>
Why not just create a simple container POJO class (or record in Java 16+) for the two maps instead of mainMap and keep the relevant type-safety which to do it Java-way?
public class MapPojo {
private final Map<String, List<String>> colMap;
private final Map<String, String> appMap;
public MapPojo(Map<String, List<String>> colMap, Map<String, String> appMap) {
this.colMap = colMap;
this.appMap = appMap;
}
// getters, etc.
}
MapPojo mainMap = new MapPojo(colMap, appMap);
Error you are getting because when you are doing map.get operation your reference is Just Map without any Generics which will treated as Object class's reference. You should use generics like below and it will work -
Map<String, List<String>> colMap = map.get("colMap");
for(Entry<String, List<String>> entry : colMap.entrySet())
Below is my code snippet
Map<Object, Object> gobalMap = new HashMap<Object, Object>();
Map<String, Map<String, Integer>> mp = new HashMap<String, Map<String, Integer>>();
gobalMap.put("mp",mp );
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", new HashMap<String, Integer>().put("A", 1));
error:
The method put(String, Map<String,Integer>) in the type Map<String,Map<String,Integer>> is not applicable for the arguments (String, Integer)
May I know where am doing wrong ..?
new HashMap<String, Integer>().put("A", 1)
This returns an Integer. But you want to add this to an object which stores Maps and not Integer. So that's not possible. Also as Thomas explained in the comments, your code would not work even if it compiled because put returns the previous value of the map so you will receive a NullPointerException.
I would recommend restructuring your code to make it more readable and to also make it work:
Map<Object, Object> gobalMap = new HashMap<Object, Object>();
Map<String, Map<String, Integer>> mp = new HashMap<String, Map<String, Integer>>();
gobalMap.put("mp",mp );
HashMap<String, Integer> aMap = new HashMap<>();
aMap.put("A", 1);
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", aMap);
As others have already stated new HashMap<String, Integer>().put("A", 1) returns an Integer (the previously mapped value for key "A" so null in this case) and that is not a suitable value for a Map<String, Map<String, Integer>>.
You're creating a suitable map but don't actually put it into the map so the reference to that map is lost.
Since you're probably trying to only create a nested map if it doesn't exist already try this:
((Map<String, Map<String, Integer>>)gobalMap.get("mp"))
.computeIfAbsent( "A", k -> new HashMap<String, Integer>())
.put("A", 1);
This does the following:
get and cast the map from globalMap (if you'd not be sure this can't return null you could use computeIfAbsent() here as well)
get the nested map for key "A" and if it doesn't exist create a new one, add and return it
put the value 1 for key "A" into the nested map
new HashMap<String, Integer>().put("A", 1) returns an integer, because when you put into a hashmap, you get back the previous value held by that key. As such it cannot be the value in a Map<String,Map<String,Integer>>.
Perhaps you meant to cast gobalMap to a Map<String,Map<String,Integer>>. But you are actually casting gobalMap.get("mp") to a Map<String, Map<String, Integer>>.
This, on the other hand, would compile:
((Map<String, Integer>) gobalMap.get("mp")).put("A", new HashMap<String, Integer>().put("A", 1));
though I'm not sure it does anything useful.
you missed the bracket. correct code will be:
((Map<String, Map<String, Integer>>)gobalMap.get("mp")).put("A", new HashMap<String, Integer>()).put("A", 1);
Here is what I'm trying to do.
Map<String, List<Address>> mapObj = someService.getSomeAddress();
Using above call I'm getting mapObj of type Map<String, List<Address>>
And I want to send mapObj as a parameter in a another method (that I cannot change) as a LinkedHashMap<String, List<LinkedHashMap>> which does some further processing.
Is there any way that I can solve this problem without affecting data inside mapObj?
You will need to perform a couple of conversion steps.
Convert all Address objects to LinkedHashMap objects.
Put all Map entries into a LinkedHashMap object.
For 1st one, you can write a utility method some where that can do this conversion. For example,
public static List<LinkedHashMap> addresstoMap(List<Address> addresses)
{
List<LinkedHashMap> list = new ArrayList<>();
for(Address a: addresses){
LinkedHashMap map = new LinkedHashMap();
// Add address fields to map here
list.add(map);
}
return list;
}
Then, for the 2nd step, you can do this:
LinkedHashMap<String, List<LinkedHashMap>> map = new LinkedHashMap<?,?>();
iterate through the entry sets of mapObj and put them into the above map object.
for (Map.Entry<String, List<Address>> e : m.entrySet()) {
map.put(e.getKey(), addresstoMap(e.getValue()));
}
The final map object above will contain the correct representation in the LinkedHashMap<String, List<LinkedHashMap>> datatype.
Hope this helps!
I would like to know the best way to retrieve the elements of a list inside a list.
List<Object> totalsList = new ArrayList<Object>();
Map<String, Object> grandTotalsMap = new HashMap<String, Object>();
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
Map<String, String> lineItemsMap1 = new HashMap<String, String>();
lineItemsMap1.put("amount", "$70.00");
lineItemsMap1.put("period", "Monthly");
Map<String, String> lineItemsMap2 = new HashMap<String, String>();
lineItemsMap2.put("amount", "$55.00");
lineItemsMap2.put("period", "Bi-Monthly");
items.add(lineItemsMap1);
items.add(lineItemsMap2);
grandTotalsMap.put("section" , "total per pay period amounts");
grandTotalsMap.put("title", "You'r amount");
grandTotalsMap.put("lineItems", items);
**
// I'm expecting output as: I want to create a new Map and put key-values like below:
{
amount: $70.00,
period: Monthly,
},
{
amount: $55.00,
period: Bi-Monthly,
}
**
In your case, using items.get(int index) will return a HashMap corresponding to the location in the array that map is stored. For instance, items.get(0) would return your the first map you added (lineItemsMap1) while items.get(1) would return the second map you added (lineItemsMap2).
Once you have the correct map you are looking for, you can then call the HashMap.get(String columnName) to retrieve the value you have stored.
Two different ways to access the information stored in your ArrayList are as follows:
HashMap<String, String> map = items.get(0);
String amount = map.get("amount"); // This will return '$70.00'
String period = map.get("period"); // This will return 'Monthly'
OR
String amount = items.get(0).get("amount"); // Returning '$70.00'
String period = items.get(0).get("period"); // Returning 'Monthly'
If you are looking to create a new map with these values, you can either store them in local variables (like done above) and then add the variables into the map when creating it like:
HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("newAmount", amount);
Or you can add the values by directly accessing the ArrayList when creating the map:
newMap.put("newAmount", items.get(0).get("amount"));
Hope this helps!
I have got some troubles converting each value in my HashMap to a String.
private static HashMap<String, List<Music>> musiksammlung = new
HashMap<String, List<Music>>();
This is my constructor for the HashMap. The key represents the album, the value a list of tracks from this album.
Now I want to convert each Music object to a String without creating a new HashMap, is this
possible?
I've tried it with the Iterator scheme, for loop over the entry set and so on but nothing seems to work.
Edit://
My code for the convertmethod:
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet())
formatList.put(key, musiksammlung.get(key).toString());
return musiksammlung;
}
But this always results in an error "is not applicable for the Arguments (String, String) so I have no idea. Do I have to override toString()?
You're on the right path but you need to convert the existing List<Music> to a List<String> and put the List<String> into your new HashMap.
You also then want to return your newly created HashMap<String, List<String>> instead of your original one.
public HashMap<String, List<String>> generateFormatList() {
HashMap<String, List<String>> formatList = new HashMap<String, List<String>>();
for(String key : musiksammlung.keySet()) {
// Value to store in map
List<String> value = new ArrayList<String>();
// Get the List<Music>
List<Music> musicList = musiksammlung.get(key);
for (Music m: musicList) {
// Add String of each Music object to the List
value.add(m.toString);
}
// Add the value to your new map
formatList.put(key, value);
}
// Return the new map
return formatList;
}
So answer your question:
Now I want to convert each Music object to a String without creating a
new HashMap, is this possible?
You need to create a new HashMap, because it's storing different type of value: List<Music> is different from List<String>.
Also as mentioned in my previous answer, make sure you override Music.toString() so that it returns a meaningful String for you instead of the one it inherits from its parent classes, which includes at least java.lang.Object
formatList wants a List<String>, but musiksammlung.get(key).toString() returns a String (not a List<String>). Did you mean this?
HashMap<String, String> formatList = new HashMap<String, String>();
Have you tried something like this:
Iterator<String> it = musiksammlung.keySet().iterator();
while (it.hasNext()) {
List<Music> ml = musiksammlung.get(it.next());
for (Music m : ml)
System.out.println(m.toString());
}
And of course you should override the Music#toString() method with something you could use.
Try to change your HashMap like this:
private static HashMap<String, List<Object>> musiksammlung = new HashMap<String,List<Object>>();
So you can save any kind of objects in this HashMap. Also use instanceof to check the type of the object before using it.