Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a list in java

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.

like image 719
Rishu Saxena Avatar asked Jun 22 '15 11:06

Rishu Saxena


People also ask

Can we slice ArrayList in Java?

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.

What is slicing in Java?

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].


1 Answers

A different and concise way to do that is using streams from Java 8:

List<WebElement> subElements = allElements.stream().limit(6).collect(Collectors.toList());
like image 154
Diaa Avatar answered Nov 14 '22 10:11

Diaa