Reputation: 169
I have a list which I get from the selenium-webdriver:
List<WebElement> allElements = driver.findElements(By.xpath(""));
Now I want to get the first 6 elements and print them.
Upvotes: 6
Views: 10238
Reputation: 879
A different and concise way to do that is using streams from Java 8:
List<WebElement> subElements = allElements.stream().limit(6).collect(Collectors.toList());
Upvotes: 10
Reputation: 38444
You can use List#sublist()
:
System.out.println(allElements.subList(0, 6));
Or, since you're using Webdriver, you also have Google Guava (it's a transitive dependency), so Iterables.limit()
also works and it's arguably slightly more readable and doesn't fail when the list is too short:
System.out.println(Iterables.limit(allElements, 6));
Upvotes: 8
Reputation: 3514
There are multiple ways and one of them is below:
for(int i=0; i < 6; i++) {
WebElement element = allElements.get(i);
}
Upvotes: 1
Reputation: 564
Use condition to check the for loop iteration something like,
int i=1;
for(WebElement element: allElements){
if(i==6)
break; //break the loop
system.out.println(""+element.getText());
i++;
}
Upvotes: 1