简体   繁体   中英

How to use Streams instead of a loop that contains a variable?

I developed this code to check if the string made up of parentheses is balanced. For instance,

Not balanced: ["(", ")", "((", "))", "()(", ")(", ...] .
Balanced: ["()", "()()", "(())", "(())()", ...]

I want to use a stream instead of a for-loop. There is a conditional statement inside the loop that checks when the counter variable is less than zero. I am unclear know how to include this variable in a stream.

I would welcome feedback on this. Please see my code below:

public String findBalance(String input) {
    String[] arr = input.split("");

    Integer counter = 0;

    for (String s : arr) {
        counter += s.equals("(") ? 1 : -1;
        if (counter < 0) break;
    }
    return counter == 0 ? "Balanced" : "Not Balanced";
}

Thanks in advance.

Streaming isn't a good fit. Ask yourself what would happen if you used parallelStream() . How would you handle a simple edge case?

)(

You want to detect when the count dips below 0, even if it later goes back up. It's quite difficult to do that with a parallel stream. The string is best processed sequentially.

Stream operations work best when they are independent and stateless. Stateful actions are better suited for a regular for loop like you already have.

Let's see whether Stream could fit.

  1. Sequentially , by character, maintaining a nesting stack , one would need a counter; reduction would be feasible. However the code is not much better, more verbose and slower. Exploiting parallelism would need to handle "...(" & ")...". Possible but not nice.

  2. Let's look at a more parallel approach: substituting inner reducible expressions (redex () ) recursively/repeatedly:

     public String findBalance(String input) { String s = input.replaceAll("[^()]", ""); for (;;) { String t = s.replace("()", ""); if (t.length() == s.length()) { break; } s = t; } return s.isEmpty(); }

Though a split-and-conquer parallelism is feasible here, the problem is the repetition needed for things like (()) .

For a Stream one might think of a flatMap or such. However Stream processing steps do not repeat (in the current java version), hence not easily feasible.

So a Stream solution is not fitting.

One could combine the recursion function with a Stream splitting the passed string, to use a parallel Stream, but even with 16 cores and strings of length 1000 that will not be considerably faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM