gpt4 book ai didi

Java 8 速览与 map

转载 作者:IT老高 更新时间:2023-10-28 20:57:43 25 4
gpt4 key购买 nike

我有以下情况:有一个对象列表 - ProductData 包含几个字段:

public class ProductData
{
....
private String name;
private String xref;

//getters
//setters
}

并且有返回以下对象列表的 API:

public class RatingTableRow
{
private String planName;
private String planXref;
private int fromAge;
private int toAge;
private int ratingRegion;

//constructor
//getters
//setters

}

但它返回具有空计划名称字段的对象,因为在提取此对象期间不允许这样做。我需要通过外部参照将产品数据与 RatingTableRow 链接,以便将计划名称设置到 RatingTableRow,因为稍后我需要使用此对象,因此我创建了以下代码来执行此操作:

Map<String, ProductData> productByXref = plans.stream()
.collect(toMap(ProductData::getInternalCode, Function.identity()));

return getRatingTableRows(...).stream
.filter(ratingRow -> productByXref.containsKey(ratingRow.getPlanXref()))
.peek(row -> {
ProductData product = productByXref.get(row.getPlanXref());
row.setPlanName(product.getName());
})....;

我知道 java 文档说 peek 不适合这些需求,但希望获得您关于如何以更正确的方式完成此任务的建议。

最佳答案

peek 被记录为主要用于调试目的是有原因的。

最终在 peek 内部处理的内容可能根本不适合终端操作,流只能由终端操作执行。

先假设一个简单的例子:

    List<Integer> list = new ArrayList<>();
List<Integer> result = Stream.of(1, 2, 3, 4)
.peek(x -> list.add(x))
.map(x -> x * 2)
.collect(Collectors.toList());

System.out.println(list);
System.out.println(result);

一切看起来都很好,对吧?因为在这种情况下,peek 将为 所有元素 运行。但是当你添加一个 filter 会发生什么(忘记 peek 做了什么):

 .peek(x -> list.add(x))
.map(x -> x * 2)
.filter(x -> x > 8) // you have inserted a filter here

您正在为每个元素执行 peek,但 没有收集。你确定要那个?

这可能会变得更加棘手:

    long howMany = Stream.of(1, 2, 3, 4)
.peek(x -> list.add(x))
.count();

System.out.println(list);
System.out.println(howMany);

在 java-8 中填充了列表,但在 jdk-9 中根本不调用 peek。由于您没有使用 filterflatmap 您没有修改 Stream 的大小,而 count 只需要它的大小; 因此根本不调用 peek。因此依赖 peek 是一个非常糟糕的策略。

关于Java 8 速览与 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44370676/

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