Java 8动态调用函数

时间:2018-03-20 20:08:56

标签: lambda java-8

我一直在网上搜索这个问题的一个例子,但到目前为止我还没有运气。我想使用一个Builder,但是没有对象有构建器" build"一个使用辅助函数的更复杂的函数。

例如,让我们说我有一个类从某个源获取字符串列表(为简单起见,我手动添加它们)。然后,一旦我收集了字符串,我希望可以选择在这些字符串上应用函数。下面的类实际上是伪编码的,但我认为它包含了我想要的行为:

public class StringGetter {

    private List<Function<String, String>> listOfFunctions;

    public List<String> getListOfStrings() {
       List<String> strings = new ArrayList<String>();
       strings.add(" test1");
       strings.add("test2    ");

       listOfFunctions.forEach((function) ->
           // apply function on strings
       )

        return strings;
    }

    public StringGetter withCapitalLetters() {
       listOfFunctions.add(String::toUppserCase);
       return this;
    }

    public StringGetter withTrimmed() {
       listOfFunctions.add(String::trim);
       return this;
    }

    public StringGetter withSingleQuotes() {
       listOfFunctions.add(s -> ' + s + ');
       return this;
    }
}

我怎么能这样做,所以我可以放任何我想要的辅助方法:

StringGetter sg = new StringGetter();

List<String> capitalAndTrimmed = sg.getListOfStrings()
                                        .withCapitalLetters()
                                        .withTrimmed();
System.out.println(capitalAndTrimmed);
Output: ["TEST1", "TEST2"]



List<String> capital = sg.getListOfStrings()
                             .withCapitalLetters()
System.out.println(capital);
Output: [" TEST1", "TEST2   "]



List<String> singleQuotes = sg.getListOfStrings()
                                  .withSingleQuotes();
System.out.println(singleQuotes);
Output: ["' test1'", "'test2    '"]

1 个答案:

答案 0 :(得分:1)

你可以这样做:

static public class StringGetter {

    private List<Function<String, String>> listOfFunctions = new ArrayList<>();


    public StringGetter withCapitalLetters() {
        listOfFunctions.add(String::toUpperCase);
        return this;
    }

    public StringGetter withTrimmed() {
        listOfFunctions.add(String::trim);
        return this;
    }

    public StringGetter withSingleQuotes() {
        listOfFunctions.add(s -> "'" + s + "'");
        return this;
    }

    public List<String> apply(List<String> input) {
        Function<String, String> one = listOfFunctions.stream()
                .reduce((left, right) -> left.andThen(right))
                .orElse(Function.identity());

        return input.stream().map(one::apply).collect(Collectors.toList());

    }
}

并按照以下方式使用:

 StringGetter sg = new StringGetter();

 sg.withCapitalLetters().withTrimmed();
 System.out.println(sg.apply(List.of("test")));

我会将您的实施更改为:

Function<String, String> first = Function.identity();

public StringGetter withCapitalLetters() {
   // may be do a check here so that this is not called twice
   first.andThen(String::toUpperCase);
   return this;
} 

.... other methods

public List<String> apply(List<String> input) {
    return input.stream().map(first::apply).collect(Collectors.toList());
}