Handling list of elements in selenium

There are 3 ways to select a list of web elements 1.First method is to first select the outer box and then use driver.findElements(By.tagname" ") on this outer box.

WebElement box = driver.findElement(By.xpath("//*[@id='popular_cat']"));
List<WebElement> items = box.findElements(By.tagName("a"));

2.Second method is to divide the common xpath into two parts and then go through each item Example if a no of items has a common xpath where only difference is a number after h3 tag like h3[1],h3[2],h3[3]... Then we can design xpath like below

String part1="//*[@id='popular_cat']/h3[";
String part2 = "]/a";
int i =1;
while(isElementPresent(part1+i+part2)){
String text = driver.findElement(By.xpath(part1+i+part2)).getText;
System.out.println("Text for element  "+i + " is " +  text);
i++;
}
}

And we define isElementPresent method like this

public static boolean isElementPresent(String xpath){
List<WebElement> allElements = driver.findElements(By.xpath(xpath));
if(allElements.size()==0)
return false;
else
return true;
}

3.Third method is to simply find the list by not putting the variable in xpath that is varying like in this case h3[1],h3[2],h3[3]... 1,2,3 is varying so xpath will be

List<WebElement> allLinks = driver.findElements(By.xpath("//*[@id='popular_cat']/h3/a"));
System.out.println(allLinks.size());