java8从命令变为功能

时间:2016-12-21 12:14:13

标签: java java-8 java-stream

以下是我强制性的代码风格

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>

3 个答案:

答案 0 :(得分:3)

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

我试试看:

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]));

答案 1 :(得分:0)

以下是您可以尝试的代码:

IntStream.of(sundayOpenAreas.size())
                    .filter(i -> {
                        String postcode = "XX" + i + " 1AA";
                        return sundayDeliveryAvailable(String.valueOf(i), postcode);
                    })
                    .forEach(System.out::println);

答案 2 :(得分:0)

试试这个:

    IntStream.range(0, sundayOpenAreas.size())
    .forEach(idx -> {
        sundayOpenAreas.stream()
        .map(x -> "XX" + idx + "".concat("1AA"))
        .filter(x -> sundayDeliveryAvailable(sundayOpenAreas.get(idx), x)).forEach(System.out::println);
    });