String name = "";
String width = "";
String height = "";
List<WebElement> imageName = driver.findElements(By.cssSelector("div.card-arago div.hover-info div.name"));
List<HashMap> imageInfo = new ArrayList<HashMap>();
HashMap<String, String> attributes = new HashMap<String, String>();
imageInfo.add(attributes);
for (WebElement image : imageName) {
attributes.put("name",image.getText());
}
List<WebElement> images = driver.findElements(By.cssSelector("div.card-arago a img"));
for (WebElement image : images) {
attributes.put("width", image.getAttribute("width"));
attributes.put("height", image.getAttribute("height"));
}
I'm trying to return all the images from the page, but it only returns the last image card on the page?
A HashMap can only store one value with each key. If you call put with the same key more than once, each call overwrites the previous. You are calling attributes.put("name", ...) multiple times in a loop, so the value attached to the key "name" gets replaced over and over again, and at the end of the loop is just left with the last image. If you actually want all images to be returned, you either need unique keys for each image, or an entirely separate HashMap for each image, depending on how you want to structure this.
EDIT: after looking at your code a bit more, it looks like you do want a List of HashMaps. But you only ever add one single HashMap to that List. Instead, you could change that first loop to add a new HashMap for each image.
When calling put(k,v);, the key is stored and the value is the extra metadata. Just a key and a value.
If I call put(1, 2); and then call put(1, 3); the value returned by get(1); will be 3. the put(k,v); function only stores different objects within the HashMap. You can not have the same values within the same HashMap, however, you can have the same values within the same HashMap.
To solve your problem, I suggest you use an identifier such like
attributes.put("width" + someIntIdentifier, image.getAttribute("width");
You are using a map and keep updating the key values , for one key a map can have only one value (it replaces the previous value). Alternatively you may try using a List of map, which will contain your map containing info about image.
String name = "";
String width = "";
String height = "";
List imageNameList = new ArrayList(); // creating list to store imageName
List imageAttributesList = new ArrayList(); // creating list to store image height and width
List<WebElement> imageName = driver.findElements(By.cssSelector("div.card-arago div.hover-info div.name"));
List<HashMap> imageInfo = new ArrayList<HashMap>();
imageInfo.add(attributes);
for (WebElement image : imageName) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("name",image.getText());
imageNameList.add(attributes); // adding map to list
}
List<WebElement> images = driver.findElements(By.cssSelector("div.card-arago a img"));
for (WebElement image : images) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("width", image.getAttribute("width"));
attributes.put("height", image.getAttribute("height"));
imageAttributesList.add(attributes); // adding map to list
}
System.out.println(imageNameList); // this will give you a list of Map having "name" key
System.out.println(imageAttributesList); // this will give you a list of Map having "height" and "width" of image
Here I have created two List to store image name and height & width . Like this you can get attributes of all the images you needed.
If I understand what you're attempting to do, I agree with jthomas about returning a list of HashMaps. Additionally, rather than managing and looping a list of elements with the name text and then separately finding and looping the dimensions of the image element, you should be able to consolidate a bit if, I assume, both of those elements are within a common div. I would do something like this:
List<HashMap> images = new ArrayList<HashMap>();
List<WebElement> imageDivs = driver.findElements(By.cssSelector("div.card-arago");
for (WebElement imageDiv : imageDivs) {
HashMap<String, String> attributes = new HashMap<String, String>();
attributes.put("name", imageDiv.findElement(By.cssSelector("div.name").getText();
WebElement image = imageDiv.findElement(By.tagName("img");
attributes.put("width", image.getAttribute("width"));
attributes.put("height", image.getAttribute("height"));
images.add(attributes);
}
The images list would then give you a hashmap for each image card on the page, each of which contained the name, height, and width of that image. Then you could iterate that list as you please.
You could try using Multimap which stores multiple values for single key.
https://guava.dev/releases/23.0/api/docs/com/google/common/collect/Multimap.html
Related
I would like to create multiple hashmaps from a resultset.
The final result should be something like below;
{
slot_name = recommend,
data = 7,
},
{
slot_name = service,
data = Good,
},
{
slot_name = staff,
data = Great,
},
I tried as below:
HashMap<String, String> data = new HashMap<String, String>();
while (resultSet.next()) {
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
}
But when I printout the value of the hashmap, I get one record as below
System.out.println(data);
{
slot_name = staff,
data = Great,
}
How can I achieve this? Someone assist, thank you
I would recommend to have a list and create a model class(instead of HashMaps) for "slot_name" and "data". Inside loop, construct object and add to the list. The reason, you are not getting as expected, is because, HashMap will have unique keys. So, for the same key when the value is again added, it will get updated.
class YourModel {
String slotName;
String data;
}
// inside loop
list.add(new YourModel(resultSet.getString("name"), resultSet.getString("param_value"));
A HashMap is a key value store. If you put the same key more than once, previous will be overwritten. This is the reason you saw only the last entry in the output.
if you want multiple maps, well create multiple ones.
Eg.,
List<HashMap<String,String> maps = new ArrayList();
while (resultSet.next()) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("slot_name", resultSet.getString("name"));
data.put("data", resultSet.getString("param_value"));
maps.add(data);
}
I am using Arraylist < HashMap< String, String >> in ListView to archive multi-column(I just need two column, so I use HashMap). But when I am using remove method in context menu. It would always remove the last item in the list.
The code:
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.bc_contextmenu_delete:
list.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
What should I do to solve this problem to remove the selected one from the list?
Besides, I would also like to get those two values from the HashMap which in the ArrayList. Which code should I use here.
Here is an ArrayList:
PS4 4000<br>
PS5 5000<br>
XBOX 6000<br>
I would like to get PS4 and 4000.
Thanks all.
As per your requirement, you can create a bean for same. i.e. DummyBean. it has two field like
class DummyBean{
String name;
String val;
--getter setter method
}
Use it into List<DummyBean>.
In future if new column added than it is easy to add and expandable.
No need to wrap the HashMap into an ArrayList. HashMap itself is enough. If you want to remain the order, you should use LinkedHashMap.
A side effect is that you cannot access elements by index, so you have to iterate over it to get the last item or the one by index.
So if you don't care about duplicates I would use ArrayList with as template a Pair or a custom Object. (Where I prefer a custom object to be more readable)
ArrayList<Pair<String,String>> consoles = new ArrayList<Pair<String,int>>();
consoles.Add(Pair.create("PS4", 4000));
consoles.Add(Pair.create("PS5 ", 5000));
consoles.Add(Pair.create("XBOX ", 6000));
And remove using index:
consoles.Remove(index);
To store and retrieve your values from the Hashmap in ArrayList, You need to store the the HashMap values with keys to identify them
As with your example ,
PS4 4000
PS5 5000
XBOX 6000
ArrayList<HashMap<String ,String>> list = new ArrayList<>();
// to add item
HashMap<String ,String> val = new HashMap<>();
val.put("GAME", "PS4");
val.put("NUMBER", "4000");
list.add(val); //added to 0th index position
val = new HashMap<>();
val.put("GAME", "PS5");
val.put("NUMBER", "5000");
list.add(val); //added to 1st
// to retrieve ps4 and 400
String forPS4 = list.get(0).get("GAME");
String for4000 = list.get(0).get("4000");
I have created the data structure as shown below that is google based guava table and it is shown below
final Table<String, String, List<String>> values = HashBasedTable.create();
values.put("bon", "currency", Lists.newArrayList("ccdd","rode1","cwey","Certy"));
below is the way in which i am iterating over this collection
Map <String , List<String>>fmap = new HashMap < String , List<String>>();
for (Cell<String, String, List<String>> cell1: values.cellSet()){
if (cell1.getRowKey() != null && cell1.getRowKey().equalsIgnoreCase("bon") )
{
fmap.put(cell1.getColumnKey(), cell1.getValue());
}
}
now i want to modify my condition in such a way that if row key contains the value of bon
and the column key contains these values "ccdd","rode1","cwey","Certy" then it should fill the map
named fmap such that on iteration map would look like this
Key Value
ccdd currency
rode1 currency
cwey currency
Certy currency
please advise how to achieve this
as the solution advise is still not working please
Instead of iterating through all the values in the Guava Table. Try to get the row with row key bon and then loop through the valid column keys to populate your map.
Map <String , List<String>>fmap = new HashMap < String , List<String>>();
List<String> validColumnKeys = Arrays.asList("ccdd","rode1","cwey","Certy");
Map<String, List<String>> row = values.row("bon");
for(String columnKey:validColumnKeys) {
fmap.put(columnKey, row.get(columnKey));
}
I'm using List of Map in java but I get a trouble. I use :
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
ArrayList<Map<String,AttributeValue>> maps = new ArrayList<Map<String,AttributeValue>>();
I use CSVReader to reading file and store values in ListOfMap
CSVReader reader = new CSVReader(new FileReader("data1.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
item.clear();
item.put("Id", new AttributeValue().withN(nextLine[0]));
item.put("Name", new AttributeValue().withS(nextLine[1]));
System.out.println("Item:"+item); // I try printing item
maps.add(item);
}
And Result is :
Item:{Id={N: 0,}, Name={S: goGOv,}}
Item:{Id={N: 1,}, Name={S: TBlGD,}}
Item:{Id={N: 2,}, Name={S: OtXuw,}}
...
Item:{Id={N: 999,}, Name={S: QAMzc,}}
Item:{Id={N: 1000,}, Name={S: PumAq,}}
But when I print some element from this List
System.out.println(" "+maps.get(i)); // I tried i from 0-1000
It always show only 1 ouput
{Id={N: 1000,}, Name={S: PumAq,}}
So anyone can show me where I'm wrong.
Thank you,
You are using same map to store all elements, but at start of each iteration you are calling item.clear(); which removes previously stored elements inside map. What you should do is create new, separate map instead of reusing old one, so change
item.clear();//don't reuse previously filled map because it still is the same map
into
item = new HashMap<>();//use separate map
You keep using the same Map object. These are persistant objects. You'll have to instantiate a new HashMap() instead of calling clear() on the existing one.
Otherwise you'll simply clear the HashMap inside of the List as well, because they refer to the same object.
I have two value objects and i have to write a file using free marker while i am writing it using simply java i am able to iterate the list but don't know how to iterate a map whick consist a variable as well as a list. in my one value object BranchArea i have variable like name and id and a list of Branch. Branch is another value object who as a variable like name etc. i am iterating in java like this
List <BranchArea> branchAreaList = new ArrayList<BranchArea>();
Iterator<BranchArea> itrBranchArea = branchAreaList.iterator();
while (itrBranchArea.hasNext()) {
BranchArea branchAreaObj = itrBranchArea.next();
LOGGER.error("Branch Area Name is"+branchAreaObj.getBranchAreaName());
Iterator<Branch> itrBranch = branchAreaObj.getBranches().iterator();
while(itrBranch.hasNext()){
Branch branchObj = itrBranch.next();
LOGGER.error("Branch Name is"+branchObj.getBranchName());
}
}
branchAreaList Consist object of BranchArea. For Ftl i convert the branchAreaList into map
HashMap<String, List<BranchArea>> branchAreaMap = new HashMap<String, List<BranchArea>>();
branchAreaMap.put("branchAreaList", branchAreaList);
How can i iterate them in Ftl as i iterate it above
You can iterate over keys of your Map, and get the elements by this way:
<#list branchAreaMap?keys as key>
${key} = ${branchAreaMap[key])}
</#list>