与Java 8流的生成器模式 [英] Builder pattern with a Java 8 Stream

查看:146
本文介绍了与Java 8流的生成器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的循环构建一个对象:

I am building an object with a simple loop:

WebTarget target = getClient().target(u);

for (Entry<String, String> queryParam : queryParams.entrySet()) {
    target = target.queryParam(queryParam.getKey(), queryParam.getValue());
}

我想用Java8 Stream API做同样的事情,但我无法想象如何做到这一点。让我奋斗的是每次都重新分配目标,所以一个简单的.forEach()将不起作用。我想我需要使用.collect()或reduce(),因为我正在寻找单个返回值,但我现在迷路了!

I want to do the same thing using the Java8 Stream API but I cannot figure out how to do it. What makes me struggle is that target is reassigned every time, so a simple .forEach() will not work. I guess I need to use a .collect() or reduce() since I am looking for a single return value but I am lost at the moment!

推荐答案

很遗憾,流API中没有 foldLeft 方法。 Stuart Marks 这个答案

There's unfortunately no foldLeft method in the stream API. The reason for this is explained by Stuart Marks in this answer:


[...]最后,Java不提供 foldLeft foldRight 操作,因为它们暗示了本质上顺序的特定操作顺序。这与上述设计原则相冲突,即提供支持顺序和并行操作的API。

[...] Finally, Java doesn't provide foldLeft and foldRight operations because they imply a particular ordering of operations that is inherently sequential. This clashes with the design principle stated above of providing APIs that support sequential and parallel operation equally.

最终你要做的是什么这里是程序/顺序的东西所以我不认为流API非常适合这个用例。我认为你自己发布的每个循环都是最好的。

Ultimately what you're trying to do here is something procedural / sequential so I don't think the stream API is a good fit for this use case. I think the for-each loop that you have posted yourself is as good as it gets.

更新:

正如@TagirValeev指出低于,你可以实际解决它与流API(使用 forEachOrdered 。您的代码看起来像

As @TagirValeev points out below you can in fact solve it with the stream API (using forEachOrdered. Your code would then look something like

WebTarget[] arr = { getClient().target(u) };
queryParams.entrySet()
           .stream()
           .forEachOrdered(e -> arr[0] = arr[0].queryParam(e.getKey(),
                                                           e.getValue()));
WebTarget target = arr[0];

我支持我的原始答案,并声称在这种情况下你的老式for-loop是一种更好的方法。

I stand by my original answer though, and claim that your good old for-loop is a better approach in this case.

这篇关于与Java 8流的生成器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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