我有一个接受字符串并返回转换后的字符串的接口(interface)
我有一些类会以不同的方式进行转换。 在 Java 中有什么方法可以创建这些类的流并转换字符串。
例如:
class MyClass implements MyOperation {
String execute(String s) { return doSomething(s); }
}
class MyClass2 implements MyOperation {
String execute(String s) { return doSomething(s); }
}
ArrayList<MyClass> operations = new ArrayList<>();
operations.add(new MyClass());
operations.add(new MyClass2());
...
operations.stream()...
我可以制作一个流以便对单个字符串进行大量转换吗?我考虑过 .reduce()
但它对数据类型很严格。
最佳答案
您的类都实现了转换 String
的方法到 String
.换句话说,它们可以用 Function<String,String>
来表示。 .它们可以按如下方式组合并应用于单个字符串:
List<Function<String,String>> ops = new ArrayList<> ();
ops.add (s -> s + "0"); // these lambda expressions can be replaced with your methods:
// for example - ops.add((new MyClass())::execute);
ops.add (s -> "1" + s);
ops.add (s -> s + " 2");
// here we combine them
Function<String,String> combined =
ops.stream ()
.reduce (Function.identity(), Function::andThen);
// and here we apply them all on a String
System.out.println (combined.apply ("dididi"));
输出:
1dididi0 2
关于java - 操作链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061120/