How to compare elements inside List of strings with Array List of string?

Karma Abdelazeez :

I have added products to my basket and listed their URL in a List and want to verify these products against given String[] of products the items are stored backwards in z String[] so the last item here is the 1st item in the List .. the number of items is 3 and below code works for 2 items and throw invoker exception at the assert method in the third item

public void verifyBag(String[] goods) {
    actions.clickOn(By.xpath(bagLocator));
    Arrays.sort(goods);
    List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
    List <String> actualItems = new ArrayList<String>();
    for(int i=0;i<listItems.size();i++)
    {
        actualItems.add(listItems.get(i).getAttribute("href"));
    }
    int j = goods.length-1;
    for(int i=0;i<goods.length;i++) 
    { 

        String actualItem = actualItems.get(i);
        String product = goods[j];
        System.out.println(product);
        //assertTrue(actualItems.get(i).contains(goods[j]));
        assertTrue(actualItem.equals(product));
            j--;        
        } 
        assertEquals(listItems.size(), goods.length,"Assert Number of Items in the Bag");
    }
Kiril S. :

If you don't care about the order, but about the match between provided list of goods and actualItems, you can do this:

  1. Convert input array String[] goods into some collection, for example List. Lets call it goodsList.
  2. From goodsList, remove all items that are also in actualItems.

    • If resulting set is empty, it means all items from goodsList are also in actualItems.
    • If resulting set is not empty, it will contain list of items that are missing in actualItems comparing to goodsList
  3. You can also do the reverse: from actualItems, remove all items that are also contained in goodsList. That gives you list of items that were not present in provided list.

Code:

public void verifyBag(String[] goods) {
    actions.clickOn(By.xpath(bagLocator));
    List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
    List <String> actualItems = new ArrayList<String>();
    for(int i=0;i<listItems.size();i++)
    {
        actualItems.add(listItems.get(i).getAttribute("href"));
    }
    List<String> goodsList = new ArrayList(Arrays.asList(goods));
    goodsList.removeAll(actualItems);
    if(goodsList.size() == 0) {
        // All goods from provided goods list are also in actualItems
    }
    else {
        // Some items didn't match
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=106945&siteId=1