Home > Back-end >  Why could the filtered elements from a Java stream return an empty list after a String was converted
Why could the filtered elements from a Java stream return an empty list after a String was converted

Time:05-16

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:

[]
[]
[]
[]
[]
[]
[]
[]
[]

The 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);
    }
  }

CodePudding user response:

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());
  • Related