简体   繁体   中英

How to use Java lambda Expressions for regular expressions

In below code i am getting all elements from the list and splitting the text after "(" .

for (WebElement element : measureKeys) {
    String[] measure = element.getText().split("\\(");
    testing.add(measure[0])
}

How to use lambdas for above code

You could essentially turn the body of the loop to a lambda expression and collect the the results

List<String> testing = 
    measureKeys.stream()
               .map(e -> element.getText().split("\\(")[0])
               .collect(Collectors.toList());

Another alternative is ,

List<String> list= Pattern.compile("\\(")
                      .splitAsStream(measureKeys)
                      .collect(Collectors.toList());
    List<String> measureKeys = new ArrayList<>();
    List<String> a = new ArrayList<>();
    measureKeys.forEach(element -> a.add(element.split("\\(")[0]));

Is that your wish ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM