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.
As a result you created problems for yourself with an unnecessary constraint that the list is an ArrayList . That works by making a copy of the sublist. It is not a slice in the normal sense. Furthermore, if the sublist is big, then making the copy will be expensive.
In Java, array slicing is a way to get a subarray of the given array. Suppose, a[] is an array. It has 8 elements indexed from a[0] to a[7]. a[] = {8, 9, 4, 6, 0, 11, 45, 21} Now, we want to find a slice of the array index from a[3] to a[6].
A different and concise way to do that is using streams from Java 8:
List<WebElement> subElements = allElements.stream().limit(6).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With