javaperformanceoptimizationjava-8java-stream

How can I use stream for a recursion in Java 8 to find groups of elements between "START" and "END"?


I have a method like this where I'm using recursion with normal loop:

// example for the args: "START" "RUN" "RUN" "END" "RUN" "START" "RUN" "END" "RUN"
// expect: Listof.("START" "RUN" "RUN" "END", "START" "RUN" "END")
static List<String[]> findValidCommands(String[] args, List<String[]> listCommands) {
    for (int i = 0; i < args.length; i++) {
        if (args[i].matches("START")) {
            for (int j = i + 1; j < args.length; j++) {
                if ("END".equals(args[j])) {
                    listCommands.add(Arrays.copyOfRange(args, i, ++j));
                    return findValidCommands(Arrays.copyOfRange(args, j, args.length), listCommands);
                }
            }
        }
    }
    return listCommands;
}

I'm a beginner. Please help me to improve my code with Stream.


Solution

  • The code cannot be improved by Stream logic, quite the opposite.

    It can however be improved by not using nested loops and not using recursion.

    static List<String[]> findValidCommands(String... args) {
        List<String[]> listCommands = new ArrayList<>();
        for (int start = -1, i = 0; i < args.length; i++) {
            if (start == -1 && args[i].equals("START")) {
                start = i;
            } else if (start != -1 && args[i].equals("END")) {
                listCommands.add(Arrays.copyOfRange(args, start, i + 1));
                start = -1;
            }
        }
        return listCommands;
    }
    

    Test

    List<String[]> listCommands = findValidCommands(
            "START", "RUN", "RUN", "END", "RUN", "START", "RUN", "END", "RUN");
    System.out.println(listCommands.stream().map(Arrays::toString).collect(Collectors.joining(", ")));
    

    Output

    [START, RUN, RUN, END], [START, RUN, END]