Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do conditional operation in java 8 stream to skip next stream operation?

In Traditional way I have written this simple java for loop

public String setString(String string) {  
StringBuilder stringBuilder = new StringBuilder();

    // This for loop I want to convert into stream. 
    for (char c : string.toCharArray()) {
       if (Character.isSpaceChar(c))
           stringBuilder.append(c);
       else if (isBangla(c))
           stringBuilder.append(get(c));
    }
    return stringBuilder.toString();
}

String get(int c) {
    return keyMap.getMap((char) c); // Map<Character, String> keyMap
}

boolean isBangla(int codePoint) {
    return ((codePoint >= BANGLA_CHAR_START && codePoint <= BANGLA_CHAR_END) &&
        (codePoint <= BANGLA_NUMBER_START || codePoint >= BANGLA_NUMBER_END)));
}

I have tried to something like this.

String str = string.chars()
            .filter(i -> Character.isSpaceChar(i)) // if this is true need to add string 
            .filter(this::isBangla)
            .mapToObj(this::get)
            .collect(Collectors.joining());

What I am trying to do is if the first filter detect it is a spaceChar then it will not do any further stream processing rather it jump into the collect.

So how could I achieve this kind of if/else situation to skip next stream operation ? Thanks in advance.

like image 829
seal Avatar asked Nov 01 '25 12:11

seal


1 Answers

Well, you could probably use something like this:

String str = string.chars()
           .filter( ch -> Character.isSpaceChar(ch) || isBangla(ch) )
           .mapToObj( ch -> isBangla(ch) ? get(ch) : Character.toString((char)ch))
           .collect(Collectors.joining());

As you can see, this stream checks isBangla twice. The first time is to leave only characters which are either space or bangla in the stream, the second one in order to know which of them to convert.

Because stream operations are independent - each stream doesn't know what happened in the stream before it - such operations may be more efficient when written in a traditional loop. What's more, you are creating a lot of little strings when you run this in a stream, where you have to convert all characters into strings, not just the bangla ones.

It's important to note that you're not "skipping" anything here. In a traditional loop, you can skip operations. But in a stream, skipping elements means that they will not be in the final result. What you do in a stream is pass those elements unchanged (or in this case, changed from a char to a String), not skip.

like image 99
RealSkeptic Avatar answered Nov 04 '25 02:11

RealSkeptic