Currently I used nested for-each loop to achieve the same.
List<String> valueListToBeFilter = Arrays.asList("8 digit mobile number", "Please enter mobile number.");
List<String> newfoundValueList = new ArrayList<>();
for (String value : valueListToBeFilter) {
for (WebElement element : _webElementsErrorList) {
if (element.getText().contains(value))
newfoundValueList.add(element.getText());
}
}
newfoundValueList.forEach(System.out::println);
I am getting the required result, but how to achieve the same using stream
CodePudding user response:
It may be better to swap map
and filter
in the "nested" stream to reduce the code a little bit more, but generally it's a minor improvement:
List<String> newfoundValueList = valueListToBeFilter
.stream()
.flatMap(value -> _webElementsErrorList
.stream()
.map(WebElement::getText)
.filter(elementText -> elementText.contains(value))
)
.collect(Collectors.toList());
CodePudding user response:
Should work with .flatMap
and another stream of the WebElement
-List like this:
List<String> newfoundValueList = valueListToBeFilter.stream()
.flatMap(value -> _webElementsErrorList.stream()
.filter(element -> element.getText().contains(value))
.map(element -> element.getText()))
.collect(Collectors.toList());