DataTable to list of maps - java

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}

Related

how to retrieve value from specific columns of excel using spring rest

Below is my controller code and service code. The service code is returning only the last value of the map, though I am adding it in the for loop. Not sure what I missing. Also in the postman, I am not getting any response, just the success code as 200. At least I should be getting the last value. The expected output is the following:
"testCaseId": "TA_SCEN01",
"testCaseDescription" : some test
"executionStatus": "Yes",
"executionBrowser": "Chrome"
Please excuse me for the long desciption of the problem statement. I just tried to give as much info for better understanding.
the controller code is below
#RestController
public class ExcelController {
#Autowired
ExcelService service;
#GetMapping(value="/{excelSheetName}/{sheetName}", produces = "application/json")
public ResponseEntity<List<Map<String, String>>> getExcelDetails(#PathVariable("excelSheetName") String excelSheetName, #PathVariable("sheetName") String sheetName) {
service.getExcelDetails(excelSheetName, sheetName);
return new ResponseEntity<List<Map<String, String>>>(HttpStatus.OK);
}
}
The service code is below
public List<Map<String, String>> getExcelDetails(String excelSheetName, String sheetName) {
//Map<String, String> map = new LinkedHashMap<String, String>();
//List list = new LinkedList<Object>();
List list = new LinkedList<Object>();
String excelPath = "C:\\Users\\140117\\Desktop\\NSARF\\Successfactor_TalentAcquisition_TestCase.xls";
FileInputStream fis;
try {
fis = new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet = workSheet.getSheetAt(0);
ExcelDetail excelObj = new ExcelDetail();
String testId = "testCaseId";
String testDesc = "testCaseDescription";
String status = "executionStatus";
String browser = "executionBrowser";
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
Map map = new LinkedHashMap();
//Map<String, String> map = new LinkedHashMap<String, String>();
Cell tcId = sheet.getRow(i + 1).getCell(0);
Cell desc = sheet.getRow(i+1).getCell(1);
Cell execStatus = sheet.getRow(i + 1).getCell(2);
Cell execBrowser = sheet.getRow(i+1).getCell(5);
if(null != tcId || null != desc || execStatus != null || execBrowser != null) {
map.put(testId, tcId.toString());
map.put(testDesc, desc.toString());
map.put(status, execStatus.toString());
map.put(browser, execBrowser.toString());
list.add(map);
}else {
break;
}
//list.add(map);
System.out.println(list);
}
//list.add(map);
System.out.println(list);
return list;
}

Clear an arraylist after return statement

I have a method that returns an ArrayList. I want to clear or re-initialise the the array list after the return statement so that the old data is not repopulated. I know we can use arrayList.clear() statement but I am not sure where to place it in the code so that the re-initialization happens after returning the array list .
My code snippet :
public static List<HashMap<String, String>> GetDataIteration(String strDataSheetPath, String sTCID) {
HashMap<String, String> hm;
//List<Map<String, String>> hmList = new ArrayList();
//List<HashMap<String, String>> hmList = new ArrayList<HashMap<String, String>>();
try {
String sTestDataFile ="C:\\AutomationGoldCopy\\IEDSS_Automation\\src\\TestData\\Support\\Support_TC_001_AddUserBuildProfile1.xlsx";
File file = new File(sTestDataFile);
FileInputStream inputstream = new FileInputStream(file);
Workbook wb = null;
if (sTestDataFile.contains(".xlsx"))
{
wb = new XSSFWorkbook(inputstream);
} else if (sTestDataFile.contains(".xls"))
{
wb = new HSSFWorkbook(inputstream);
}
Sheet sheet = wb.getSheetAt(0);
int count = sheet.getPhysicalNumberOfRows() ;
System.out.println(count);
for (int i=1 ; i <count ; i++)
{
Row headerrow = sheet.getRow(0);
hm = new HashMap<String, String>();
System.out.println(i);
Row currentRow = sheet.getRow(i);
for (int j = 0; j < headerrow.getPhysicalNumberOfCells(); j++)
{
Cell currentCell = currentRow.getCell(j,Row.CREATE_NULL_AS_BLANK);
hm.put(headerrow.getCell(j).toString(), currentCell.toString());
}
//hmList.clear();
hmList.add(hm);
for (HashMap<String, String> h : hmList) {
for (String key : h.keySet()) {
System.out.println(key + "\t" + h.get(key));
}
System.out.println("\n");
}
// hmList.clear();
}
} catch (Exception e) {
System.out.println(e);
}
return hmList;
}
Kindly help me with the same.
main method :
public static void main(String[] args) {
String dtDataSheetPath = null;
String dtTestCaseID = null;
List<HashMap<String, String>> TestDataList = Excel.GetDataIteration(dtDataSheetPath,dtTestCaseID);
for(Map<String, String> TestData : TestDataList) {
String name = TestData.get("TestCase Name");
String name1 = TestData.get("SMU_LastName");
System.out.println( "Got it : " + name + " " + name1);
}
There are three rows in the excel . The first is the hearder row and the last two rows are the header values.
I am converting the excel rows into a hashmap with header row as keys and the second and third rows as values of the hashmap.
In the second run ( when i =2 ) , the first row is repopulated again. I just wanted the second row. When I clear the ArrayList hmList , it works fine but I wanted to return the list too.
In your function the initialization hmList = new ArrayList>(); creates a new empty List each time the function is called so there is no need to clear it after the return statement (which, anyway, is not possible in the same function).
As hmList seems to me a static variable you can return a copy of this list and clear the hmList before the return, if your specification says hmList should be empty by the return of your function.

Android : HashMap is showing only last array item in a Listview field

I'm prsing information from a json file and showing data in a custom ListView. Now, I have an Array named authors. Where authors are multiple. But, in ListView I can only see the last authors name or last array item .
How can I show all items ? Here is my code
for (int index = 0; index < jsonArray.length(); index++)
{
HashMap<String, String> temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);
temp.put(KEY_AUTHOR, authordName);
That's probably why. You are iterating over the all authors but HashMap will override values and only the last one is being saveed.
As I understand you are getting back a JSON response with an array of JSONObject. Each JSONObject holding some info and a sub-JSONArray of associated authors.
The easiest approach could be just building ArrayList<JSONObject> and extending BaseAdapter implementing an adapter of your own. It's very easy. For large collections of data search on ViewHolder pattern, for optimization.
'HashMap<String, String> temp;
for (int index = 0; index < jsonArray.length(); index++)
{
temp = new HashMap<String,String>();
JSONObject jsonObject = jsonArray.getJSONObject(index);
String topic = jsonObject.getString("topic");
String type = jsonObject.getString("type");
String title = jsonObject.getString("title");
String absData = jsonObject.getString("abstract");
JSONArray getAuthorsArray = new JSONArray(jsonObject.getString("authors"));
for(int a =0 ; a < getAuthorsArray.length(); a++){
JSONObject getJSonObj = (JSONObject)getAuthorsArray.get(a);
String authordName = getJSonObj.getString("name");
Log.e("Name", authordName);
temp.put(KEY_AUTHOR, authordName);
}
temp.put(KEY_TOPIC, topic);
temp.put(KEY_TYPE, type);
temp.put(KEY_TITLE, title);
temp.put(KEY_ABSTRACT,absData);
list.add(temp);
}
}
simpleAdapter = new SimpleAdapter(this, list, R.layout.abstract_items, from, new int[]{R.id.abTopic,R.id.abType,R.id.abTitle,R.id.SubTitle});
setListAdapter(simpleAdapter);'
you declare the "HashMap"line in above the onstart values.it will help for you.

how to get hashmap content of arraylist in 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.

Java -for loop only repeating last value

I have an Array to hold the value from DB. If I try with some default data it working fine but if I get value from DB, its only showing last value.
Default Data;
MenuList menu_data [] = new MenuList[]{};
menu_data = new MenuList[]
{
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1") ,
new MenuList("test","test1")
};
Value from DB,
MenuList menu_data [] = new MenuList[]{};
List<Menu> profiles = db.getAllContacts();
for (Menu cn : profiles) {
menu_data = new MenuList[]
{
new MenuList(cn.getmenuname(), cn.getmenuprice())
};
}
How do I get all the value from DB.
Everytime you go through the loop, you are creating a new array. Hence, only the last value is available. Please try the following
menu_data = new MenuList[profiles.size()];
for (int i = 0; i < menu_data.length; i++) {
Menu cn = profiles.get(i);
menu_data[i] = new MenuList(cn.getmenuname(), cn.getmenuprice());
}
Try this:
List<MenuList> menulists = new ArrayList<MenuList>();
for (Menu cn : db.getAllContacts())
menulists.add(new MenuList(cn.getmenuname(), cn.getmenuprice()));
MenuList[] menu_data = menulists.toArray(new MenuList[0]);
List<Menu> profiles = db.getAllContacts();
int numProfiles = profiles.size();
MenuList[] menu_data = new MenuList[numProfiles];
for (int i = 0; i < numProfiles; i++) {
Menu cn = profiles.get(i);
menu_data[i] = new MenuList(cn.getmenuname(), cn.getmenuprice());
}

Categories

Resources