简体   繁体   English

Java8 Lambda顺序或管道字符串转换

[英]Java8 lambda sequential or piped String transformation

I work on a JCR- based application, and my query breaks when it contains illegal characters. 我在基于JCR的应用程序上工作,当查询中包含非法字符时,查询就会中断。

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: 我想使用lambda,但有点卡住了:

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: lambda内部的查询变量是J8不满意的,导致出现以下错误:

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. 问题在于您正在lambda表达式主体的范围内访问局部变量query It therefore must be final or effectively final . 因此,它必须是final或实际上是final However, declaring query as final would not solve the problem since you're assigning a value to it. 但是,将query声明为final并不能解决问题,因为您正在为其分配值。

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. 我建议您让方法replaceCharacter使用StringBuilder并让它替换内容,而不是读取并重新分配String变量。

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. 是的,我开始更深入地研究-并尝试使用StringBuilder,但是由于我需要替换字符串中的所有出现,因此需要使用另一个嵌套循环将其迅速升级为10多行代码。

Thus, instead of reducing complexity and improving code readability, that was doing right the opposite. 因此,与其相反,不是降低复杂性和提高代码的可读性。

Compare to the lambda-free one: 与无lambda比较:

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! 经验教训:不管这些鞋有多时尚,都不要试图像拉姆达一样shoe脚!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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