小编Yek*_*soy的帖子

如何编写返回具有 java8 功能的字符串的 for 循环?

基本上我想要做的是用java 8特性编写一个像下面这样的for循环,

private String createHashCode() {
    for (int i = 0; i < MAX_TRY; i++) {
        final String hashCode = createRandomString();
        if (!ishashCodeExistence(hashCode)) {
            return hashCode;
        }
    }
    throw new HashCodeCollisonException();
}
Run Code Online (Sandbox Code Playgroud)

我试过的是;

private String createHashCode() {
    IntStream.range(0, MAX_TRY).forEach($ -> {
        final String hashCode = createRandomString();
        if (!ishashCodeExistence(hashCode)) {
            return hashCode;
        }
    });
    throw new HashCodeCollisonException();
}
Run Code Online (Sandbox Code Playgroud)

但是,lambda 中的 foreach 方法返回 void,因此我无法返回字符串。

有什么方法可以编写我的方法而不是使用普通的 for 循环?

java for-loop java-8 java-stream

-1
推荐指数
1
解决办法
83
查看次数

标签 统计

for-loop ×1

java ×1

java-8 ×1

java-stream ×1