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.
Related
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.
So I'm going crazy with this one. This is for an assignment and can't seem to get this to work at all!!
I have the following HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team being another class to obtain the details of the teams)
What I need to be able to do is get the List of teams for the Key(String) from the above HashMap, and assign the List to a local variable I have declared:
List<Team> results = teams.get(division);
But this is where I get stuck. I have no idea how I'm suppose to complete this task.
As a further note "division" is the Key used in the HashMap. The ArrayList is a list of teams that belong to the division.
I have tried the below, which does not compile at all. Really not sure how I can get this to work!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**You can ignore the arguments after the "String division". These will be used later.
Iterate over the entrySet() of the Map. Now you can fetch each List for that specific key and proceed further. Something like:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}
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);
I created a HashMap to store a text file with the columns of information. I compared the key to a specific name and stored the values of the HashMap into an ArrayList. When I try to println my ArrayList, it only outputs the last value and leaves out all the other values that match that key.
This isn't my entire code just my two loops that read in the text file, stores into the HashMap and then into the ArrayList. I know it has something to do with my loops.
Did some editing and got it to output, but all my values are displayed multiple times.
My output looks like this.
North America:
[ Anguilla, Anguilla, Antigua and Barbuda, Antigua and Barbuda, Antigua and Barbuda, Aruba, Aruba, Aruba,
HashMap<String, String> both = new HashMap<String, String>();
ArrayList<String> sort = new ArrayList<String>();
//ArrayList<String> sort2 = new ArrayList<String>();
// We need a try catch block so we can handle any potential IO errors
try {
try {
inputStream = new BufferedReader(new FileReader(filePath));
String lineContent = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
String column[]= lineContent.split(",");
both.put(column[0], column[1]);
Set set = both.entrySet();
//Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if(me.getKey().equals("North America"))
{
String value= (String) me.getValue();
sort.add(value);
}
}
}
System.out.println("North America:");
System.out.println(sort);
System.out.println("\n");
}
Map keys need to be unique. Your code is working according to spec.
if you need to have many values for a key, you may use
Map<key,List<T>>
here T is String (not only list you can use any collection)
Some things seems wrong with your code :
you are iterating on the Map EntrySet to get just one value (you could just use the following code :
if (both.containsKey("North America"))
sort.add(both.get("North America"));
it seems that you can have "North America" more than one time in your input file, but you are storing it in a Map, so each time you store a new value for "North America" in your Map, it will overwrite the current value
I don't know what the type of sort is, but what is printed by System.out.print(sort); is dependent of the toString() implementation of this type, and the fact that you use print() instead of println() may also create problems depending on how you run your program (some shells may not print the last value for instance).
If you want more help, you may want to provide us with the following things :
sample of the input file
declaration of sort
sample of output
what you want to obtain.
I have the following list:
List<ArrayList> list;
list.get(i) contains the ArrayList object with the following values {p_name=set1, number=777002}.
I have to create a
Map<key,value>
where the key contains the p_name, and values are the numbers.
How to do it easily and fast as there can be hundreds of entries in the initial list and each number can be present in multiple p_name entries.
Update: Here is my current solution
List<Row> list; //here is my data
Map<String,String> map = new TreeMap<String,String>();
for (Row l : list) {
if (l.hasValues()) {
Map<String, String> values = l.getResult(); // internal method of Row interface that returns a map
String key = values.get( "number");
map.put(key, values.get( "p_name" ));
}
}
The method works, but maybe it could be done better?
PS : There is an obvious error in my design. I wonder if you find it :)
Sine the key can have more then one values, what you are looking for is a MultiMap. Multimap
Or a simple map in the form
Map<Key,ArrayList<Values>>
There is no "fast" way here to me. You still need to iterate through all the elements and check all the values.
And actually hundreds to Java is not much at all