如何在Java 8中创建漂亮的迭代 [英] How to create nice iterations in Java 8

查看:139
本文介绍了如何在Java 8中创建漂亮的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Adam Bien的博客启发,我想取代一个共同点在Java 7中将Java 7中的迭代转换为更好的代码。旧代码如下所示:

Inspired by Adam Bien's weblog I wanted to replace a common iteration in Java 7 into a nicer one in Java 8. The older code looked like this:

void repeatUsingJava7(int times) {
    for (int i = 0; i < times; i++) {
        doStuff();
        doMoreStuff();
        doEvenMoreStuff();
    }
}

...这不太好。所以我用Adam Bein的例子替换它:

...which is not too nice. So I replaced it using Adam Bein's example into this:

void repeatUsingJava8(int times) {
    IntStream.range(0, times).forEach(
        i -> {
            doStuff();
            doMoreStuff();
            doEvenMoreStuff();
        }
    );
}

...这是向正确方向迈出的一步,但没有做出代码更容易阅读,并且还引入了一个不需要的变量 i ,以及一对额外的花括号。所以现在我想知道是否有其他方法来编写这个代码,这将使它更好更容易阅读,主要是使用Java 8.

...which is a step in the right direction, but does not make the code much simpler to read, and also introduces an unneeded variable i, as well as an extra pair of curly brackets. So now I'm wondering if there are other ways to write this code which will make it even nicer and easier to read, primarily using Java 8.

推荐答案

为了完整起见,这里有一个不需要计数器变量的解决方案:

Just for completeness, here is a solution which doesn’t need the counter variable:

void repeatUsingJava8(int times) {
    Collections.<Runnable>nCopies(times, ()->{
        doStuff();
        doMoreStuff();
        doEvenMoreStuff();
    }).forEach(Runnable::run);
}

如果只有一个方法可以调用多个,那么它会变得更具可读性在这种情况下可以写成,例如

It would become more readable if there is only one method to be invoked multiple times as in that case it could be written as, e.g.

void repeatUsingJava8(int times) {
    Collections.<Runnable>nCopies(times, this::doStuff).forEach(Runnable::run);
}

如果必须 Stream s,上面的代码相当于

If it has to be Streams, the code above is equivalent to

void repeatUsingJava8(int times) {
    Stream.<Runnable>generate(()->this::doStuff).limit(times).forEach(Runnable::run);
}

然而,这些替代方案并不比好老的<$ c $更好c> for 循环。如果你考虑 parallel 执行,这是 Stream 的真正优势,而不是普通的 / code>循环,仍有基于众所周知的已批准API的替代方案:

However, these alternatives are not really better than the good old for loop. If you consider parallel execution, which is a real advantage of Streams over ordinary for loops, there are still alternatives based on commonly known, approved APIs:

ExecutorService es=Executors.newCachedThreadPool();
es.invokeAll(Collections.nCopies(times, Executors.callable(()->{
    doStuff();
    doMoreStuff();
    doEvenMoreStuff();
})));

这篇关于如何在Java 8中创建漂亮的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆