How to short List having WebElement inside it - java

I am getting some value from a HTML Table. I am able to print the values but not able to figure out a way by which i can sort them alphabetically.
Code which i used-
List<WebElement> lst = driver.findElements(By.xpath(".//*[#class='user-questions lines']/tbody/tr/td[2]"));
for(WebElement s : lst) {
System.out.println(s.getText()); //This line prints the value
String[] ss = new String[lst.size()];
int i=0;
if(s.getText() != null) {
ss[i]=s.getText();
System.out.println(ss[1]); // But here i am getting null
}
i++;
}
First i tried to sort it using Collections.sort(lst) but got an error message:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (List).
Then i tried to put the string value inside a String array and later sort it but here i am getting null value when i tried to put the value into the String array

Today i was stuck in the same thing and found this question asked a way back at the start of this year. When i tried the solutions given i got a NullPointerException.
I wrote a small code and now i am able to short the webelements accoriding to the Natural alphabetical order. Here is the code-
//Here storing the WebElements in the List
List<WebElement> lst = driver.findElements(By.xpath("WebElement XPath"));
//Here creating a String array
String[] str = new String[lst.size()];
for (int i = 0 ; i<str.length ; i++){
str[i] = driver.findElements(By.xpath("WebElement XPath")).get(i).getText();
}//for
Arrays.sort(str);
for(String strr: str){
System.out.println(strr);
}
driver_1.close();
driver_1.quit();
}//try
catch(Exception e){
e.printStackTrace();
driver.close();
driver.quit();
}//catch
First i stored the webelements in the List. Then i created a String array for sorting.In the first for loop i stored the string which i got from the website. After that i sorted them using Arrays.sort method
In the advance for loop i am printing the output.
As i can see the question is very old and if during this time you got much better answer then please share it.

You getting null at System.out.println(ss[1]);
because:
ss[i]=s.getText(); always put in ss[0], because: before if int i=0;.
So ss[1] always empty.
To solve it put int i=0; before for(WebElement s : lst)

Declare i outside foreach loop. and sysout ss[i]. On your first loop execution obviously ss[1] will be null.
Another way around is:
List<WebElement> lst = driver.findElements(By.xpath(".//*[#class='user-questions lines']/tbody/tr/td[2]"));
String[] str = new String[lst.size()];
int i = 0;
for (WebElement ele : lst) {
if(ele.getText()!=null)
str[i] = ele.getText();
i++;
}
Arrays.sort(str); // to sort the array of strings

Related

get element from ArrayList (java)

Struggling with what is probably a simple query to match and return an element in an ArrayList.
I first store a HashSet in the ArrayList because HashSet has no get method and then check the ArrayList (which contains the correct elements, strings of socket references).
List theseSocks = new ArrayList(NodeConnMaster.sockList);
System.out.println("array list contains " + theseSocks);
I then want to iterate through and find the matching ipAddress in the element and once found set a variable to the entire element, so something like -
for (int i =0; i< theseSocks.size(); i++) {
if (theseSocks.toString().contains(ipAddress)) {
int element = theseSocks.get();
System.out.println("the element is " + element);
}
}
but it appears that get needs an index position and I am trying to get based on string contents, not index.
Is there an easier way than deleting all the elements except the matching one and then returning index 0.
Or is ArrayList not the way to go.
The solution was, with SBylemans's help -
Object currentSock = null;
for (int i =0; i< theseSocks.size(); i++)
{
currentSock = theseSocks.get(i);
if (currentSock.toString().contains(ipAddress))
{
System.out.println("the element is " +currentSock);
break;
}
}
Regards
Ralph
You can use stream of Java8 for filtering required elements like:
List wantedList = theseSocks.stream()
.filter(e ->e.toString().contains(ipAddress))
.collect(Collectors.toList())
You're looping over the ArrayList and want to compare based on the String value. But looping like this will immediately also give you the index. Your loop should look something like this:
for (int i =0; i< theseSocks.size(); i++)
{
String currentSock = theseSocks.get(i);
if (currentSock.equals(ipAddress))
{
System.out.println("the element is " +currentSock);
break;
}
}
Or even with a forEach loop
for (String currentSock: theseSocks)
{
if (currentSock.equals(ipAddress))
{
System.out.println("the element is " +currentSock);
break;
}
}
The break is used to interupt the for loop once your element is found.
Additionaly, your if condition will cause a print of every element if the array contains the ipAddress you're looking for.
Edit And then when using java 8, you can also use streams as posted by others.

sorting list of values in java after converting string to integer

I am doing some selenium automation test case and i am getting list of web element using the below code.
List<WebElement> list = GlobalVariables.BrowserDriver.findElements(By.xpath(".//*[#id='Tbls_T']/tbody/tr/td[4]"));
and then i am iterating that web element and getting the values using
for (WebElement webElement : list) {
System.out.println(webElement.getText());
}
so i am getting the values in string format. and sample values are giving below
-100,000
-80,000
0.100
2
87.270
3,000.000
I want to check these values in sorting order or not? for that i think i should convert to integer and then check using some kind of sorting method i guess. for that i have tried to convert the values to a list of integer and then use some sorting algorithm like Guava to check the sorting. because of negative values i am facing difficulty to do that.
Is there any way i can check the sorting order for the above problem and check the order of the values. ?
thanks in advance.
You want to just check the incoming list is sorted or not.
You compare the previous value with current value. If previous value is greater than current value then the list is not sorted.
Sample code:
WebElement prev=null;
boolean isSorted = true;
for (WebElement currentWebElement : list) {
if (prev == null) {
prev = currentWebElement;
continue;
} else {
if (Double.compare(Double.parseDouble(prev.getText().replaceAll(",", "")),
Double.parseDouble(currentWebElement .getText().replaceAll(",", ""))) > 0) {
isSorted = false;
break;
}
prev = currentWebElement;
}
}
create 2 copies of your data
convert the first to integers and sort it
convert the second one to integers and leave it
check if the two lists are equal if they are then your list is sorted
Please use another list of doubles and Collections.sort(). You may have to remove the commas from strings
public class ConvertToIntSort
{
public static void main( String[] args )
{
String[] strlist = {"-100000","0.100", "2" , "3000.000","87.270", "-80000" };
java.util.List<String> stringlist = Arrays.asList(strlist);
java.util.List<Double> intList = new ArrayList<Double>();
for(String str : stringlist)
{
//converting and adding to double list
intList.add(Double.valueOf(str));
}
//Sorting is done here
Collections.sort(intList);
for(Double num : intList)
{
System.out.println(num);
}
}
}

Elements are not being removed from ArrayList

I am trying to remove elements that do not contain a specific string from an arrayList but with no luck. I am using the following code:
ArrayList<String> classes = ClassesRetrieval.getYagoClasses();
Iterator<String> it = classes.iterator();
while(it.hasNext()){
if(it.next().contains("yago")){
it.remove();
}
}
for(String i : classes){
System.out.println(i);
}
I also tried
for(int i=0;i<classes.size();i++){
if(!classes.get(i).contains("yago")){
classes.remove(i);
}
}
for(String i : classes){
System.out.println(i);
}
but with no luck..
I tested you first code on a list I created myself. It worked, but if you want to remove Strings that don't contain "yago", you are missing a !.
ArrayList<String> classes = ClassesRetrieval.getYagoClasses();
Iterator<String> it = classes.iterator();
while(it.hasNext()){
if(!it.next().contains("yago")){
it.remove();
}
}
for(String i : classes){
System.out.println(i);
}
First of all, remove '!' in your second code if(!classes.get(i).contains("yago")), and i think it should work.
If it won't, give some base code of ClassesRetrieval.getYagoClasses();, please.
Using for loops to remove elements is really not recommended. Consider having two consecutive strings, both of which contain "yago". It will remove the first one, increment i and skip the second string (since it now has the index of the first string).
Try a while loop where you increment only if you don't remove the element (or, if you hate branching, reverse the for loop from greater to smaller).
As for your first example, right now it removes all those that do contain "yago". If you put a ! before the condition it should work properly.
I don't see anything wrong with your syntax/logic. However, it is possible that the condition
!classes.get(i).contains("yago")
Is not being met. To test whether this is true, I would print something if the condition yields true. For example:
for(int i=0;i<classes.size();i++){
if(!classes.get(i).contains("yago")){
classes.remove(i);
System.out.println("Condition Met");
}
}
You can even print the deleted element like this:
for(int i=0;i<classes.size();i++){
if(!classes.get(i).contains("yago")){
System.out.println(classes.remove(i));
}
}
I hope you find this helpful.
The second piece of code you showed should work. Why are you using the negation (!) in your for loop?
I think that what you wanted is:
for(int i=0; i<classes.size(); i++){
if(classes.get(i).contains("yago")){
classes.remove(i);
}
}
The problem with this approach is that when you remove an element from the list you change it's size. You could instead create an empty ArrayList and keep adding new elements to it if it does not obey the condition:
List<String> tmp = new ArrayList();
for(String token : classes){
if(!token.contains("yago")){
tmp.add(token);
}
}
for(String i : tmp){
System.out.println(i);
}
It might make since to iterate in reverse to avoid index problems. Try something like this:
for(int i=classes.size()-1; i>=0; i--)
{
//get a string from list
String s = classes.get(i);
if(!s.contains("yago"))
{
//if the string does not contain yago, remove it
classes.remove(i);
}
}

Verify over 200 List elements on a page in Webdriver

I have some 200 elements who's mark-up is as follows:
<span id="1356329740258" class="pagename">Sport & leisure</span>
<span id="1356329740259" class="pagename">Food & drink</span>
<span id="1356329740260" class="pagename">Household</span>
<span id="1356329740261" class="pagename">Gardening</span>
I can access them with Webdriver in a fairly ugly manner:
List<WebElement> elements;
elements = driver.findElements(By.xpath( ".//*[starts-with(#id, '135')]"));
...Because each starts with a '135'.
But driver.findElement(By.cssSelector(".pagename");
...does not work, perhaps something to do with the '' tags
What I now need to do, is do a .getText() for each element in the list and verify it against the expected, corresponding array value. I'm starting off thinking of this method:
String[] expected = {"Sport & leisure", "Food & drink", "Household", "Gardening"};
List<WebElement> elements = select.find.Elements(By.xpath( ".//*[starts-with(#id,'135')]"));
// compare #array items with #found elements in List
if (expected.length != elements.size()) {
System.out.println("the wrong number of elements were found");
}
// check value of every pagename class element equals expected value
for (int i = 0; i < expected.length; i++) {
String elementsValue = elements.get(i).getAttribute("value");
if (elementsValue.equals(expected[i])) {
System.out.println("passed on: " + elements);
} else {
System.out.println("failed on: " + elements);
}
}
This has the obvious limitation of potentially having to store 200 odd text strings in the array and will therefore become unwieldy. Is there a more elegant solution? I could read the array values in from a .csv I guess and used Parameterized runner but then I'd still need to declare each value in the constructor right?
You can use the Lists contains or containsAll function to determine equality. So basically like this:
final List<String> expectedElements = readFromCSV("expectedElements.csv");
final List<WebElement> elements = select.find.Elements(By.xpath( ".//*[starts-with(#id,'135')]"));
final List<String> stringElements = new ArrayList<>(elements.length);
for (WebElement element : elements) {
stringElements.add(element.getAttribute("value"));
}
final boolean isSame = stringElements.containsAll(expectedElements);
This is not a direct answer to your question, but only a few corrections to your code:
1.
You can replace the code that you consider "ugly":
List<WebElement> elements = select.findElements(By.xpath(".//*[starts-with(#id,'135')]"));
With a code that finds the elements using their class attribute:
List<WebElement> elements = select.findElements(By.xpath("//span[#class='pagename']"));
2.
Since non of these elements has a value attribute, you should replace the following line:
String elementsValue = elements.get(i).getAttribute("value");
With:
String elementsValue = elements.get(i).getAttribute("innerHTML");

How to get the list elements at each index separately using java

How to Print the list elements separately using Java
.i.e., I have a list of elements with different calculatedvalue and different updatevalues. I want to display calvalue1 and updateval1 separately into two different variables say calvalue1 into double calValue and updateval1 into double updateValue.And the loop should iterate until list becomes empty.Can anyone provide me the logic please help me.
list has at 1st line 0.98 and 23/12/2005 (list.get(0))
at 2nd line 2.3 and 08/09/2013 (list.get(1))
and so on
//here WebAvail is my class
List<WebAvail> list= new List<WebAvail>();
String query="select calvalue,updateval from sample where url='www.abc.com';
list=session.createQuery(query).list;
for(int i=0;i<list.size();i++)
{
for(int j=0;j<list.get(i);j++)
{
list.get(j);
}
}
i.e., list.get(0) gives me 1st line of the list.In that line I am having calvalue1 and updateval1 say 0.98 and 23/12/2005.I need those values seperately i.e., 0.98 into one variable and 23/12/2005 into another variable(that is I want to access seperately).list.get(0).get(0) is not valid.
How can I get that one.And also If I do like in the above code snippet It is giving me "ClassCastException:unable to cast java.lang.object to java.util.list".Here I am not having problem with query and execution of query.I checked the list by forwarding it to jsp.And jsp displaying list values.But I want list elements in WebAvail separately as I mentioned above.
for(int i=0;i<list.size();i++)
{
String a[] = list.get(j).toString().split(",");
Double a1 = Double.parseDouble(a[0].toString());
String a2 = a[1].toString();
}
Is your list.get(0) also returning the list? In this case, you can do the following:
double calValue;
Date updateval1;
List listEle = null;
for(int i=0;i<list.size();i++){
listEle = (List) list.get(i);
if(null != listEle){
if(listEle .get(0) instanceof Double)
calValue = (Double) listEle .get(0);
if(listEle .get(1) instanceof Date)
updateval1 = (Date) listEle .get(1);
}
}

Categories