how to get hashmap content of arraylist in java? - java

I am using the following code to save hashmap content into arraylist.
HashMap jediSaber = new HashMap();
ArrayList<HashMap> valuesList = new ArrayList();
for(int i = 0; i< 4;i++) {
jediSaber.put("white","white_name"+i);
jediSaber.put("blue","blue_name"+i);
valuesList.add(i, jediSaber);
System.out.println("list ontent:"+i+":"+valuesList.get(i).values());
}
`
output is as follows:
list content:0:[blue_name0, white_name0]
list content:1:[blue_name1, white_name1]
list content:2:[blue_name2, white_name2]
list content:3:[blue_name3, white_name3]
When i try to display the content of arraylist in outside with the following code,
System.out.println("list content:");
for(int i = 0;i<valuesList.size();i++){
System.out.println("list:"+i+":"+valuesList.get(i).values());
}
It is showing the following output,
list content:0:[blue_name3, white_name3]
list content:1:[blue_name3, white_name3]
list content:2:[blue_name3, white_name3]
list content:3:[blue_name3, white_name3]
My problem is i need to display the content of arraylist of hashmap.
I think something i missed in second part. Can anybody help me to solve this minor issue?
Thanks in advance!!..

This is adding the same HashMap each time to the ArrayList:
valuesList.add(i, jediSaber);
Create a new HashMap each time within the for and add it:
List<HashMap<String, String>> valuesList =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 4; i++)
{
HashMap<String, String> m = new HashMap<String, String>();
m.put("white", "white_name" + i);
m.put("blue", "blue_name" + i);
valuesList.add(m);
}
System.out.println(valuesList.toString());

List<Map> valuesList = new ArrayList();
for (int i = 0; i < 4; i++) {
Map<Object, Object> jediSaber = new HashMap<>();
jediSaber.put("white", "white_name" + i);
jediSaber.put("blue", "blue_name" + i);
valuesList.add(jediSaber);
Set<Entry<Object, Object>> entrySet = jediSaber.entrySet();
for (Entry<Object, Object> entry : entrySet) {
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}

Try pulling jediSaber inside your for loop, like so:
for(int i = 0; i < 4; i++) {
Map<String, String> jediSaber = new HashMap<String, String>();
You should also parameterize valuesList too:
List<Map<String, String>> valuesList = new ArrayList<Map<String, String>>();
P.S. There's no need to call add(i, jediSaber) with the index argument: valuesList.add(jediSaber) will have the same effect.

Related

DataTable to list of maps

I have this kind of a table to deal with:
The path for the headers is:
List<WebElement> headers;
headers = driver.findElements(By.xpath("//*[#id=\"table1\"]/thead/tr/th"));
The path for the table body is:
List<WebElement> dataTable;
dataTable = driver.findElements(By.xpath("//*[#id=\"table1\"]/tbody/tr/td"));
List of headers has size of 6, list of dataTable has size of 24.
I am trying to put this to a list of maps
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
So far I've managed to add just the first entry:
for (int i = 0; i < headers.size(); i++) {
mapa.put(headers.get(i).getText(), dataTable.get(i).getText());
}
and the output is:
{Last Name=Smith, First Name=John, Email=jsmith#gmail.com, Due=$50.00, Web Site=http://www.jsmith.com, Action=edit delete}
But if I put it to the loop where row size = 4, it will give me a list of 4 same maps.
What do I have to do to make it work? I would like to have that kind of format (list of maps) so I can send it as a JSON in API POST testing.
Thank you for your help!
Example input
class WebElement {
private final String text;
public WebElement(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
List<WebElement> header = List.of(
new WebElement("Last Name"),
new WebElement("Name"),
new WebElement("Email"),
new WebElement("Due"),
new WebElement("Web Site"),
new WebElement("Action")
);
List<WebElement> dataTable = List.of(
new WebElement("Smith"),
new WebElement("John"),
new WebElement("jsmith#gmail.com"),
new WebElement("$50.00"),
new WebElement("http://www.jsmith.com"),
new WebElement("edit delete"),
new WebElement("Pippo"),
new WebElement("Pluto"),
new WebElement("pippo.pluto#gmail.com"),
new WebElement("$40"),
new WebElement("http:pippo.com"),
new WebElement("edit"),
new WebElement("Ciao"),
new WebElement("Adam"),
new WebElement("adam.ciao#gmail.com"),
new WebElement("$60"),
new WebElement("http://ciao.com"),
new WebElement("delete")
);
List<Map<String, String>> listOfMaps = new ArrayList<>();
for(int i = 0; i < dataTable.size(); i = i + header.size()) {
Map<String, String> mapa = new HashMap<>();
for(int j = 0; j < header.size(); j++) {
mapa.put(header.get(j).getText(), dataTable.get(i + j).getText());
}
listOfMaps.add(mapa);
}
Example output:
listOfMaps.forEach(map -> System.out.println(map));
{Action=edit delete, Email=jsmith#gmail.com, Web Site=http://www.jsmith.com, Due=$50.00, Last Name=Smith, Name=John}
{Action=edit, Email=pippo.pluto#gmail.com, Web Site=http:pippo.com, Due=$40, Last Name=Pippo, Name=Pluto}
{Action=delete, Email=adam.ciao#gmail.com, Web Site=http://ciao.com, Due=$60, Last Name=Ciao, Name=Adam}

.replace(list(x), "") Doesn't Work Java

I wrote code:
List<String> Names = new ArrayList<String>();
List<Double> Prices = new ArrayList<Double>();
List<String> Dates = new ArrayList<String>();
List<String> Hours = new ArrayList<String>();
List<String> iDs = new ArrayList<String>();
SimpleAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView resultsListView = (ListView) findViewById(R.id.listMyReceipts);
SearchView m = (SearchView) findViewById(R.id.action_search);
HashMap<String, String> NamePrice = new HashMap<>();
TextView test = (TextView) findViewById(R.id.test);
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("9:33");
Names.add("Apple Store"); Prices.add(500.00); Dates.add("01/01/2017"); Hours.add("9:30");
Names.add("Esselunga"); Prices.add(135.67); Dates.add("01/01/2017"); Hours.add("11:51");
Names.add("Mediaworld"); Prices.add(19.98); Dates.add("01/01/2017"); Hours.add("12:03");
Names.add("Starbucks"); Prices.add(11.99); Dates.add("01/01/2017"); Hours.add("12:47");
for (int i = 0; i < Names.size(); i++) {
iDs.add(";+#:" + i + ":#+;");
NamePrice.put(iDs.get(i) + Names.get(i), " " + Prices.get(i).toString() + "€" + " - " + Dates.get(i) + " " + Hours.get(i));
}
List<HashMap<String, String>> listItems = new ArrayList<>();
adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
new String[] {"First", "Second"},
new int[] {R.id.listitemTitle, R.id.listitemSubItem});
//Integer x = 0;
//int x = -1;
Iterator it = NamePrice.entrySet().iterator();
for (int i = 0; i < iDs.size(); i++) {
HashMap<String, String> resultMap = new HashMap<>();
Map.Entry pair = (Map.Entry) it.next();
resultMap.put("First", pair.getKey().toString().replace(iDs.get(i), ""));
resultMap.put("Second", pair.getValue().toString());
listItems.add(resultMap);
}
//test.setText(IDs.get(x - 1));
resultsListView.setAdapter(adapter);
}
This should replace all the IDs into "". It doesn't. So the output could be: ;+#:0:#+;NAME1 12.99 ;+#:1:#+;NAME2 0.99
But in the second loop, if I say
resultMap.put("First", pair.getKey().toString().replace(IDs.get(0), ""));
it replaces correctly the element 0.
The output would be: NAME1 12.99 ;+#:1:#+;NAME2 0.99
You are not getting the entries of NamePrice in the order you expect. I inserted a System.out.println() in your second for loop and got the output in this order:
;+#:3:#+;Mediaworld
;+#:0:#+;Starbucks
;+#:4:#+;Starbucks
;+#:1:#+;Apple Store
;+#:2:#+;Esselunga
So you are trying to replace ;+#:0:#+; in ;+#:3:#+;Mediaworld and so forth. That doesn’t replace anything. The reason is that NamePrice is a HashMap. A HashMap’s iterator does not return the entries in any specific order, particularly not in the order they were inserted.
You may use a LinkedHashMap instead:
LinkedHashMap<String, String> NamePrice = new LinkedHashMap<>();
Its iterator returns the entries in the order they were created. So now the replacements work.

ArrayList of HashMaps to string, and then back to ArrayList of HashMaps

I have a ArrayList<HashMap<String,String>> that I am using the toString() method on to store in a database.
Here is the code that I use to store it the toString() to a database (it works):
HashMap<String, String> commentsHash = null;
ArrayList<HashMap<String, String>> test2 = new ArrayList<HashMap<String, String>>();
for (int i=0; i < test.size(); i++)
{
String timestamp = test.get(i).get("timestamp");
String last_name = test.get(i).get("last_name");
String first_name = test.get(i).get("first_name");
String comment = test.get(i).get("comment");
commentsHash = new HashMap<String, String>();
commentsHash.put("creation_timestamp", timestamp);
commentsHash.put("first_name", first_name);
commentsHash.put("last_name", last_name);
commentsHash.put("comment", comment);
test2.add(commentsHash);
}
dbHelper.addCommentsToMyLiPost(Integer.parseInt(sqlId), test2.toString());
Here is the method I want to use to convert a string to a HashMap<String, String>:
protected HashMap<String,String> convertToStringToHashMap(String text){
HashMap<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=1; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;
}
I have tried using .split(",") on the string to split the string into 2 parts, but instead of returning two, it returns 8.
Here is what the toString() method prints. It is an ArrayList of HashMaps, and I am trying to grab the two HashMaps that are inside of the ArrayList.
[{comment=hello, last_name=u1, first_name=u1, creation_timestamp=1404938643772}, {comment=hello2, last_name=u2, first_name=u2, creation_timestamp=1404963221598}]
In convertToStringToHashMap, when you put your data into HashMap, the old value will be replaced since they have same key for each records, such as comment, last_name, etc.
public static Map<String, Map<String, String>> convertToStringToHashMap(String text)
{
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
Map<String, String> data = new HashMap<String, String>();
int gap = 8;
int key = 1;
for (int i = 1; i + 2 <= split.length; i += 2)
{
data.put(split[i], split[i+1]);
if((i + 1) % gap == 0)
{
map.put(String.valueOf(key++), data);
data = new HashMap<String, String>();
data.clear();
}
}
return map;
}
This will return a Map:
2={first_name=u2, last_name=u2, comment=hello2, creation_timestamp=1404963221598}
1={first_name=u1, last_name=u1, comment=hello, creation_timestamp=1404938643772}
This program will recreate the whole list from the database entry
Pattern firstPat = Pattern.compile("\\{.*?\\}");
Matcher firstMat = firstPat.matcher(text);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while(firstMat.find()){
HashMap<String, String> map = new HashMap<>();
String assignStrings = firstMat.group();
String [] assignGroups = assignStrings.substring(1,assignStrings.length()-1).split("\\s*\\,\\s*");
for(String assign:assignGroups){
String [] parts = assign.split("\\=");
map.put(parts[0], parts[1]);
}
list.add(map);
}
return list

ArrayList<HashMap<String,String>> to String[]

i have data fetched from my webservice in
ArrayList<HashMap<String,String>>
Now i want to convert each object of the above to
String[]
how do i do this?
any help would be much appreciated!
try
ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
HashMap<String, String> n = new HashMap<String, String>();
n.put("a", "a");
n.put("b", "b");
test.add(n);
HashMap<String, String> m = test.get(0);//it will get the first HashMap Stored in array list
String strArr[] = new String[m.size()];
int i = 0;
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
strArr[i] = current;
i++;
}
}
The uses for an Hashmap should be an Index of HashValues for finding the values much faster. I don't know why you have Key and Values as Strings but if you only need the values you can do it like that:
ArrayList<HashMap<String, String>> test = new ArrayList<>();
String sum = "";
for (HashMap<String, String> hash : test) {
for (String current : hash.values()) {
sum = sum + current + "<#>";
}
}
String[] arr = sum.split("<#>");
It's not a nice way but the request isn't it too ;)
ArrayList<HashMap<String, String>> meterList = controller.getMeter();
HashMap<String, String> mtiti = meterList.get(0);//it will get the first HashMap Stored in array list
String[] strMeter = new String[mtiti.size()];
String meter = "";
for (HashMap<String, String> hash : meterList) {
for (String current : hash.values()) {
meter = meter + current + "<#>";
}
}
String[] arr = meter.split("<#>");

How to populate a hashmap from an array

i have two arrays (actually one, but i created two for each columns). I want to populate a hashmap with the values for a listview but all elements of the listview is the last element of the arrays:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0; i<13; i++)
{
map.put("left1", date[i]);
map.put("right1", name[i]);
mylist.add(map);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, mylist, R.layout.row,
new String[] {"left1", "right1"}, new int[] {R.id.left, R.id.right});
lv1.setAdapter(simpleAdapter);
Any ideas?
Thanks
You're adding the same map to every slot of the array. Try this instead:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for (int i=0; i<13; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("left1", date[i]);
map.put("right1", name[i]);
mylist.add(map);
}

Categories

Resources