I have a List<Map> which should be of the below syntax:
[{clientName=abcd}, {clientName=defg}]
Previously I had List<Bean> which I want to replace with List<Map>.
Here is my code:
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
What happens with this code is, I am getting [{clientName=defg}, {clientName=defg}] as the output where, clientName=abcd is replaced by the 2nd value defg. How can I get the expected result which is [{clientName=abcd}, {clientName=defg}]?
Thanks
You have to re-initialize your Map<> again before adding to List<> because you are changing previous reference for Map<> object and on same key that will change previous object also.
You code should be :
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName","abcd");
clientList.add(clientNameMap);
clientNameMap = new HashMap<String,String>(); //Initialize it again.
clientNameMap.put("clientName","defg");
clientList.add(clientNameMap);
First read up on Map and List. When you add a Map object (or any other object) to a List object, all you're doing is adding a reference to that object in the List.
It means that if you change the Map contents after adding it to the List object, that will be reflected in the List.
In a Map, moreover, the key has to be unique.
So here you need to create a new Map object before you can add the new value and add that new Map object to the list.
See this other post for details:copying a java hashmap
Try below code, Map key should be unique so when you put value to same key n times the value is just replaced for the key, In your code you are replacing the value for same key(clientName) and adding it to list so it is printing the same value which you put in last to map.
List<Map> clientList=new ArrayList<Map>();
Map<String,String> clientNameMap = new HashMap<String,String>();
clientNameMap.put("clientName-1","abcd");
clientList.add(clientNameMap);
clientNameMap.put("clientName-2","defg");
clientList.add(clientNameMap);
Related
I want to know how can I retrieve values from Map<ArrayList<String>, Object> Where the String and object are stored as Array [] for user define length.
Here is an Example:
int counter=0, n=0;
if (dataSnapshot.exists()){
for (DataSnapshot ds: dataSnapshot.getChildren()){
loca[counter]= new ArrayList<>();
itemListProduct[n]= new ItemListProduct();
itemListProduct[n]= ds.getValue(ItemListProduct.class);
loca[counter].add(testHeaderlist.get(counter));
System.out.println(ds.child("item_NAME").getValue(String.class));
objectMap.put(loca[counter],itemListProduct[n]);
counter++;
}
Here the testHeaderlist is an ArrayList<String> where there are some string stored.
I wanted to store data in the below Image manner:
So now my question is how can I retrieve the Key as well as the Object from "dataList". As from the code which I have shared at the TOP "n" number of list, and the object are stored in the dataList.
The thing is that I want to retrieve to use it in ExpandableListView. loca as header and itemListproduct as my value Object. Where the both are stored at objectMap.
Can anyone please solve it. Thank you!
It is permitted but rather atypical to have an ArrayList as a key to a map. To get the Object you need to do the following:
Object val = map.get(arrayList)
Here, arrayList must contain the exact same strings in the same order as the ArrayList key which refers to the desired object.
Example
Map<List<String>, Integer> map = new HashMap<>();
List<String> key = List.of("abc", "efg");
map.put(key, 20);
Integer v = map.get(List.of("efg","abc")); // different key so
// object not found
System.out.println(v); // prints null
v = map.get(List.of("abc", "efg"));
System.out.println(v); // prints 20
You can get all the Keys of a map by doing
Set<List<String>> set = map.keySet();
You also need to readup on HashMap and ArrayList to understand how they work. The following will keep replacing the object for the key of list[0]
dataList.put(list[0], object[0]);
dataList.put(list[0], object[1]);
dataList.put(list[0], object[2]);
dataList.put(list[0], object[3]);
When the above is done, list[0] will only refer to object[3]
I want to update or create a field called "tags" inside a document, which should contain an array of custom objects called Tags ("tag_name", "tag_color"). To update or create such a field, I must pass an array of said object (not able to pass single objects, since it would be ineffective and expensive). How can I achieve this? I have tried adding an ArrayList of Tag objects to a Hashmap:
HashMap<String, ArrayList<GenericTagModel>> myObject = new HashMap<>();
ArrayList<GenericTagModel> toArrayList = new ArrayList<GenericTagModel>(usedModels);
myObject.put("tags",toArrayList);
db.collection("users").document(user.getUid()).set(myObject, SetOptions.merge());
But all this does is add a field with nothing inside of it: "tags:[]"
What can I do?
You are getting tags:[] because your toArrayList empty, does not contain any GenericTagModel objects. To solve this, please use the following lines of code:
HashMap<String, ArrayList<GenericTagModel>> myObject = new HashMap<>();
ArrayList<GenericTagModel> toArrayList = new ArrayList<GenericTagModel>(usedModels);
toArrayList.add(new GenericTagModel("redTag", "Red")); //Populate ArrayList
toArrayList.add(new GenericTagModel("blueTag", "Blue")); //Populate ArrayList
toArrayList.add(new GenericTagModel("greenTag", "Green")); //Populate ArrayList
myObject.put("tags",toArrayList);
db.collection("users").document(user.getUid()).set(myObject, SetOptions.merge());
The result will be an array that will contain theree GenericTagModel objects.
I wonder how to make a registry/database list in Java. I mean if I, for example, have a variable called "data", and then I add a new entry to that called "name" with the value "David". Then I would call something like "data.name" to get the value "David".
As seen on this picture
I've been Googling but not finding anything about it.
It sounds like you want a Map from String to String. You can use a HashMap<String,String> for that.
// Create Map using HashMap
Map<String, String> data = new HashMap<String, String>();
// Set name
data.put("name", "David");
// Get name
String name = data.get("name");
System.out.println(name);
Not sure how to phrase this question. I have a dummy code here for a bootcamp/training exercise. I have a list of hash maps that I want to set in this loop as it goes through the ingredients. The code runs without error, however all of the ingredients in the list of hash maps are always set to the last one. It appears as if each one is over writing the previous one. Here is my code:
List<Map<String,String>> returner= new ArrayList<Map<String,String>>();
Map<String,String> resultant = new HashMap<String,String>();
for ( Ingredient current : webIngredients ) {//loop through each ingredient in list of ingredients
resultant.put("Ingredient", current.getIngredientName());
resultant.put("Quantity", current.getQuantity());
resultant.put("Unit", current.getMeasureType());
recipe.getFields().add(resultant);//using a recipe. Not used in test
returner.add(resultant);//add first hashmap to the list
}//end for: loop through records (file lines)
So basically I want to read in the ingredients from the ingredient object which has three properties, ingredientname, quantity, and unit (the measurement). So if I give it lettuce,2,slice and tomato,1,slice then I should get a list with maps Ingredient:lettuce Quantity:2 Unit:slice, Ingredient:tomato quanity:1 unit:slice
Because you're only creating a single map, you are overwriting the details each time. You need to create a new map each time inside the loop:
List<Map<String,String>> returner= new ArrayList<Map<String,String>>();
for ( Ingredient current : webIngredients ) {//loop through each ingredient in list of ingredients
// create a map for this ingredient
Map<String,String> resultant = new HashMap<String,String>();
resultant.put("Ingredient", current.getIngredientName());
resultant.put("Quantity", current.getQuantity());
resultant.put("Unit", current.getMeasureType());
recipe.getFields().add(resultant);//using a recipe. Not used in test
returner.add(resultant);//add this hashmap to the list
}//end for: loop through records (file lines)
You have initialized Map<String,String> resultant = new HashMap<String,String>(); outside the for loop;
When the first time for loop run the maps get populated with certain values.
When the loop runs the second time the map object values get overridden because it's the same map object on the heap. That's why it is taking the last value;
just put the Map<String,String> resultant = new HashMap<String,String>(); inside the for loop so every time a new map object is created.
Hi I think this is very simple problem but I am not able to get through it right now;
There are two kinds of Objects-RuleObject,TaskObject
Following are definitions of RuleObject,TaskObject
RuleObject
ruleID,RulePatternType,RulePrint
TaskObject
taskID,taskName,Org,ruleID
ruleArrayList is all objects of RuleObjects
taskArrayList is all objects of TaskObjects
The final formation will be to fetch all RuleObjects used by TaskObjects and arrange by RuleObjects
like example shown below:
RuleObject.RulePatternType1
TaskName1 TaskOrg1 RUleObject.rulePrint1
TaskName2 TaskOrg2 RuleObject.rulePrint1
RuleObject.RulePatternType2
TaskName3 TaskOrg1 RUleObject.rulePrint2
TaskName4 TaskOrg2 RuleObject.rulePrint2
TaskName5 TaskOrg3 RUleObject.rulePrint2
TaskName6 TaskOrg4 RuleObject.rulePrint2
Code snippet:
List<TaskObject> taskArrayList = compModIF.getRecurringTasksForOrgsAndEffDate(allOrgIds, effDate);
List<RuleObject> ruleArrayList = compModIF.getComplianceTaskRecurrenceRules();
Map ruleTypes = new HashMap();
Map groupTaskTypes = new HashMap();
Map groupRecurRulesNames = new HashMap();
Map masterMapOfallMaps = new HashMap();
Map recurPrintMap = new HashMap();
Map recurPatternTypeMap = new HashMap();
List groupRecuringTaskTypesList = null;
Map filterRules = new HashMap();
List completedList = new ArrayList();
for(Iterator iter = ruleArrayList .iterator(); iter.hasNext();)
{
RuleObject ruleBase = (RuleObject)iter.next();
ruleTypes.put(ruleBase.getRecurRuleID(),ruleBase);
}
if (recurringTaskList != null)
{
for (Iterator it = taskArrayList .iterator(); it.hasNext();)
{
TaskObject aTaskDef = (TaskObject)it.next();
groupRecuringTaskTypesList = new ArrayList();
if(ruleTypes.containsKey(aTaskDef.getTaskRecurRuleIDAsLong()))
{
RuleObject ruleBase = (RuleObject)ruleTypes.get(aTaskDef.getTaskRecurRuleIDAsLong());
groupRecuringTaskTypesList.add(aTaskDef);
groupTaskTypes.put(ruleBase.getRecurRuleID(),groupRecuringTaskTypesList);
groupRecurRulesNames.put(ruleBase.getRecurRuleID(), ruleBase.getRecurRuleName());
if(ruleBase.getRecurPatternType()==ComplianceCodes.TASK_RECUR_PATTERN_TYPE_DAILY)
{
completedList= getDailyRecursCommentsAsCompleted(ruleBase.printRule());
recurPrintMap.put(ruleBase.getRecurRuleID(), completedList);
}
//groupRecuringTaskTypes = new ArrayList();
recurPatternTypeMap.put(ruleBase.getRecurRuleID(), ruleBase.getRecurPatternType());
}
}
}
The problem here is for 1 ruleID there are multiple arraylists because of which I am able to get the last added list.
Can any one suggest better alternative for this.
I didn't really follow your example too closely, but it sounds like what you need is a multimap - a mapping from a single key to multiple values.
Guava provides an interface for this and various implementations, usually accessed via Multimaps.
You have to store a Collection for each key:
Map<KeyType, Collection<ValueType>> map =
new HashMap<KeyType, Collection<ValueType>>()
You can attain it simply by using Object as the value. and define the Map as shown below.
Map map = new HashMap()
Then when u set an ordinary object without multiple value
set for the key and value as any valueObject
map.put("key", valueObject)
when you want to add more than one, you can check for exiting key map.containsKey("key") and then add it to an arraylist and add remaining values into this list map.put("key", valueObjectList).
Note: just make sure that when u retrive it next time, do a instanceof check before you access the value as an object or list.
Alternate soln: store value as a list of object. it is simpler to code.