简体   繁体   中英

Calling a Java 8 function only once when iterating a function list

Is there an elegant way to store the return value of the apply() method so it won't have to be invoked more than once? Because the only way I could think of is to create a local map variable that will store the function-"return value" pairs.

@Autowired
private List<Function<String, String>> evaluators; 
//...
private String evaluate(String code) {  
    return evaluators.stream().filter(f -> f.apply(code) != null).findFirst().get().apply(code); 
}

Try this.

  private String evaluate(String code) {  
      return evaluators.stream()
          .map(f -> f.apply(code))
          .filter(s -> s != null)
          .findFirst().get();
  }

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