【问题标题】:Convert below imperative java code (nested for loops) to java 8 using streams使用流将以下命令式 Java 代码(嵌套的 for 循环)转换为 Java 8
【发布时间】:2021-04-26 23:26:09
【问题描述】:

下面是嵌套 for 循环的命令式风格。我想利用 java 8 Streams 和其他特性使其成为一种功能样式。

import java.util.Arrays;

public class Java8 {

    public static final String TAILS = "TAILS";
    public static final String HEADS = "HEADS";

    public static void main(String[] args) {
        String[] coines = new String[11];
        Arrays.fill(coines, TAILS);

        for(int i=1;i<coines.length ; i++){
            System.out.println("Person :" + i);
            for (int j=1; j < coines.length ; j++){

                if(j%i==0){
                    System.out.print("Flipping " + j +"th Element from " + coines[j] + " to ");
                    coines[j] = coines[j]== TAILS ? HEADS : TAILS;
                    System.out.println(coines[j]);
                }
            }
        }
    }
}

【问题讨论】:

标签: arrays java-8 functional-programming java-stream


【解决方案1】:

我想你想做这样的事情

import java.util.Arrays;
import java.util.stream.IntStream;

public class Java8 {

public static final String TAILS = "TAILS";
public static final String HEADS = "HEADS";

public static void main(String[] args) {
    String[] coines = new String[11];
    Arrays.fill(coines, TAILS);
    IntStream.range(0, coines.length).forEach(i-> {
        System.out.println("Person :" + i);
        IntStream.range(0, coines.length).filter(j->j%i==0)
                .forEach(j -> {
                    System.out.print("Flipping " + j +"th Element from " + coines[j] + " to ");
                    coines[j] = coines[j].equalsIgnoreCase(TAILS) ? HEADS : TAILS;
                    System.out.println(coines[j]);
        });
    });
    
}}

我还将if 更改为filter== 更改为equalsIgnoreCase

【讨论】:

    【解决方案2】:

    一种方法

    IntStream.range(1, coins.length)
            .forEach(i -> {
                System.out.println("Persion :" +i);
                IntStream.range(1, coins.length)
                    .filter(j -> j%i == 0)
                    .forEach(j -> {
                        System.out.print("Flipping " + j +"th Element from " + coins[j] + " to ");
                        coins[j] = coins[j].equals(TAILS) ? HEADS : TAILS;
                        System.out.println(coins[j]);
                    });
            });
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多