gpt4 book ai didi

java8 从命令式到函数式的转变

转载 作者:行者123 更新时间:2023-11-30 07:57:28 26 4
gpt4 key购买 nike

以下是我的命令式代码风格

for (int i = 1; i <= sundayOpenAreas.size(); i++) {
String area = sundayOpenAreas.get(i - 1);
String postcode = "XX" + i + " 1AA";

boolean sundayDeliveryAvailable = sundayDeliveryAvailable(area, postcode);
Assert.assertTrue(sundayDeliveryAvailable, area + " should accept deliveries on Sunday to " + postcode + "!");
System.out.println(area + ", " + postcode);
}

想转换为函数式风格的 java8 流,以下是到目前为止的尝试

 IntStream.range(0, sundayOpenAreas.size())
.forEach(
idx -> {
sundayOpenAreas.stream()
.map(x -> "XX" + idx + "".concat("1AA"))
//Struck here on how to proceed
//System.out.println(abc);
});

哪里sundayOpenAreas is List<String>

最佳答案

首先,我认为您应该坚持命令式方法,因为管道中需要多个变量。

我会试一试:

IntStream.range(0, sundayOpenAreas.size())
.mapToObj(i -> new String[] { sundayOpenAreas.get(i), "XX" + i + " 1AA" })
.peek(s -> Assert.assertTrue(sundayDeliveryAvailable(s[0], s[1]),
s[0] + " should accept deliveries on Sunday to " + s[1] + "!"))
.forEachOrdered(s -> System.out.println(s[0] + ", " + s[1]));

关于java8 从命令式到函数式的转变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41262608/

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