我有一个接口,它接受一个字符串并返回一个转换后的字符串
我有一些类将以不同的方式转换。在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(),但它对数据类型有严格的要求。
发布于 2018-06-27 19:20:17
您的类都实现了将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发布于 2018-06-27 19:13:27
ArrayList<MyClass>应该为ArrayList<MyOperation>,否则对operations.add(new MyClass2());的调用将产生编译错误。
也就是说你在找this overload of reduce
String result = operations.stream().reduce("myString",
(x, y) -> y.execute(x),
(a, b) -> {
throw new RuntimeException("unimplemented");
});"myString"是标识值。(x, y) -> y.execute(x)是要应用的累加器函数。(a, b) -> {...是仅当流并行时使用的组合器函数。因此,对于顺序流,您不需要担心它。你可能还想读一读我之前在"Deciphering Stream reduce function".上贴出的答案
https://stackoverflow.com/questions/51061120
复制相似问题