首页
学习
活动
专区
圈层
工具
发布

运营链
EN

Stack Overflow用户
提问于 2018-06-27 19:02:08
回答 2查看 105关注 0票数 1

我有一个接口,它接受一个字符串并返回一个转换后的字符串

我有一些类将以不同的方式转换。在Java中有没有办法创建这些类的流,并对字符串进行转换。

例如:

代码语言:javascript
复制
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(),但它对数据类型有严格的要求。

EN

回答 2

Stack Overflow用户

发布于 2018-06-27 19:20:17

您的类都实现了将String转换为String的方法。换句话说,它们可以由Function<String,String>表示。它们可以按如下方式组合并应用于单个字符串:

代码语言:javascript
复制
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"));

输出:

代码语言:javascript
复制
1dididi0 2
票数 3
EN

Stack Overflow用户

发布于 2018-06-27 19:13:27

ArrayList<MyClass>应该为ArrayList<MyOperation>,否则对operations.add(new MyClass2());的调用将产生编译错误。

也就是说你在找this overload of reduce

代码语言:javascript
复制
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".上贴出的答案

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51061120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档