gpt4 book ai didi

Java 8 : Stream : Consuming steps to save Intermediate States of streamed elements

转载 作者:行者123 更新时间:2023-11-30 06:10:20 25 4
gpt4 key购买 nike

首先,对这个抽象的标题感到抱歉。这个想法通过一个例子更简单。假设我在列表 L 中有一些值。我想为服务构建参数请求,然后调用该服务并收集所有响应。

目前,我正在使用这种代码结构:

private final List<String> bodies = ImmutableList.of(
"1", "2", "3", "4"
);

@Test
public void BasicRequestResponseStreamToList() {

final List<Request> requests = bodies.stream()
.map(Request::new)
.collect(Collectors.toList());

final List<Response> responses = requests.stream()
.map(service::send)
.collect(Collectors.toList());

commonAssertions(requests, responses);

}

但是,考虑到必须在发送第一个请求之前构建最后一个请求,我发现两个流的需求效率不高。我想做类似的事情:

@Test
public void StatefulMapperStreamRequestResponseToList() {

final List<Request> requests = new ArrayList<>();
final List<Response> responses = bodies.stream()
.map(Request::new)
.map(x -> {
requests.add(x);
return service.send(x);
})
.collect(Collectors.toList());

commonAssertions(requests, responses);

}

但是,我对使用这样的“Hack”来映射语义感到内疚。然而,这是我发现用延迟加载构建 2 个相关列表的唯一方法。我对第一个解决方案不感兴趣,因为它必须在发送请求之前等待构建所有请求。我很想在 EIP 中实现类似窃听的功能。 http://camel.apache.org/wire-tap.html

我很乐意让您想到一种比修改 map 方法的语义更优雅的方式来实现这一点。

如果有帮助,您可以在这里找到源代码:http://tinyurl.com/hojkdzu

最佳答案

使用 .peek() 虽然需要对代码进行较少的更改,但实际上是一种非常肮脏的解决方案。您需要它,因为您的原始代码存在设计缺陷。你有“并行数据结构”(可能这个术语不太好):requests 列表中的第一个元素对应于 responses 列表中的第一个元素,等等在。当您遇到这种情况时,请考虑创建一个新的 PoJo 类。像这样:

public class RequestAndResponse { // You may think up a better name
public final Request req; // use getters if you don't like public final fields
public final Response resp;

public RequestAndResponse(Request req, Response resp) {
this.req = req;
this.resp = resp;
}
}

现在您的问题神奇地消失了。你可以这样写:

List<RequestAndResponse> reqresp = bodies.stream()
.map(Request::new)
.map(req -> new RequestAndResponse(req, service.send(req)))
.collect(Collectors.toList());

commonAssertions(reqresp);

之后您将需要更改 commonAssertions 方法,但我很确定它会变得更简单。此外,您可能会发现代码中的某些方法同时使用请求和响应,因此将它们作为 RequestAndResponse 类中的方法是很自然的。

关于Java 8 : Stream : Consuming steps to save Intermediate States of streamed elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com