0

I am having 2 list which contains web-element,

List<WebElement> assert_number= driver.findElements(By.xpath("//div[@class='tabs__body-inner']")) ;

assert_number: This list contains multiple brand's name.

List<WebElement>names=driver.findElements(By.xpath("//td[contains(text(),'Brand')]//following::td[1]"));

names: This is the another list which contains also some brand's name.

So , I need to compare the two list and see which all values are similar and print in the console

Please suggest me how I can do that.

Nitin Zadage
  • 633
  • 1
  • 9
  • 27
sam
  • 57
  • 6

1 Answers1

0

First of all do not store elements you need to process somehow in future as WebElements. The thing is that once any of the element is detached from DOM the reference will go stale which will lead to StaleElementException as the response to any method call of that element.

If you want to compare two lists of elements you need to extract the properties of those elements right away as soon as you have fetched them. So for example you need to compare text of elements. Then you do:

List<String> assert_number = 
        driver
        .findElements(By.xpath("//div[@class='tabs__body-inner']"))
        .stream()
        .map(webElement -> webElement.getText())
        .collect(Collectors.toList());

The same with the second list

Then you just compare two lists. This task might be solved in different ways. Depending on for example whether you want to take into account elements orders, etc. There is a dedicated thread one that topic on SO: Simple way to find if two different lists contain exactly the same elements?

If you care about order (I believe you do since elements in DOM are ordered) you can just use equals of list like shown below:

List<String> l1 = Arrays.asList("a", "b", "c");
List<String> l2 = Arrays.asList("a", "b", "c");
System.out.println(l1.equals(l2));

Output: true

List<String> l1 = Arrays.asList("a", "b", "c");
List<String> l2 = Arrays.asList("b", "a", "c");
System.out.println(l1.equals(l2));

Output: false

Alexey R.
  • 8,057
  • 2
  • 11
  • 27