'Why could the filtered elements from a Java stream return an empty list after a String was converted to List?
I accessed a web table with selenium and collected all the table rows into a list:
List<WebElement> nameColumn = driver.findElements(By.xpath("//tbody/tr/td[2]/span"));
I looped through the list, getText from the elements and stored the result in a String:
for (WebElement tdElement : nameColumn) {
String records = tdElement.getText();
//To be able to filter the result so as to collect words starting with a particular pattern, I converted the `String` to a `List`:
List<String> myList = new ArrayList<>(Arrays.asList(records.split(",")));
System.out.println(myList);
}
Output:
["test1"]
["testme"]
["demoit"]
["sampleit"]
["johndoe"]
["testeurope"]
["testusa"]
["testitaly"]
["gomali"]
Using stream(), I tried collecting elements that start with test:
List<String> filteredFields = myList.stream().filter(field -> field.startsWith("test")).collect(Collectors.toList());
System.out.println(filteredFields);
Output:
[]
[]
[]
[]
[]
[]
[]
[]
[]
An empty list was returned. Why could the filter be empty? Could it be because of the conversion of a String to a List? How do I achieve collecting all the elements that startsWith test?
The whole code bock looks like this:
public void demo() throws InterruptedException {
List<WebElement> nameColumn = driver.findElements(By.xpath("//tbody/tr/td[2]/span"));
for (WebElement tdElement : nameColumn) {
String records = tdElement.getText();
//convert to List
List<String> myList = new ArrayList<>(Arrays.asList(records.split(",")));
System.out.println(myList);
//Get elements that start with test
List<String> filteredFields = myList.stream().filter(field -> field.startsWith("test")).collect(Collectors.toList());
System.out.println(filteredFields);
}
}
Solution 1:[1]
Your arraylist contains words with quotes, i.e " test1 ".
That is why you should not check directly with field.startswith. But you should first remove quote and then check field.startswith.
Please use below :
List<String> filteredFields = myList.stream().filter(field -> field.substring(1, field.length()-1).startsWith("test")).collect(Collectors.toList());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
