简体   繁体   中英

Java8 lambda sequential or piped String transformation

I work on a JCR- based application, and my query breaks when it contains illegal characters.

So I've undertaken a really simple task: given a query string and a map containing a list of "dodgy" characters, sequentially replace those dodgy chars with allowed ones. I want to use lambdas, and am sadly a little bit stuck:

public static Map<String, String> DODGY_CHARS = getDodgyCharMapping();

static Map<String, String> getDodgyCharMapping(){
    Map<String, String> map = new HashMap<>();
    map.put("'", "''");
    return map;
}

private String sanitizeQueryString(String query){
    DODGY_CHARS.keySet().forEach(key->{
        query = replaceCharacter(query, key, DODGY_CHARS.get(key));
    });
    return query;
}

The query variable inside the lambda is what J8 is not happy with, resulting in the following error:

error: local variables referenced from a lambda expression must be final or effectively final

The problem is that you're accessing the local variable query within the scope of the lambda expression's body. It therefore must be final or effectively final . However, declaring query as final would not solve the problem since you're assigning a value to it.

I would suggest you let the method replaceCharacter takes a StringBuilder and have it replace the contents instead of reading and re-assigning the String variable.

Thanks for useful replies and comments, good people. Yes, I started digging deeper - and have tried to use StringBuilder, but since I needed to replace all occurrencies within a string, that quickly escalated to 10+ lines of code with another nested loop.

Thus, instead of reducing complexity and improving code readability, that was doing right the opposite.

Compare to the lambda-free one:

private String sanitizeQueryString(String query){
    for (String key: DODGY_CHARS.keySet()){
        query = replaceCharacter(query, key, DODGY_CHARS.get(key));
    }
    return query;
}

Nice and simple, huh?

Lesson learnt: don't try to shoe-horn everything as lambda, no matter how fashionable these are!

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