Java8 流如何用其他字符列表替换特定的字符列表

我有一个 Unicode 字符列表,需要将其替换为其他一些字符才能正常工作。但是,我必须循环两次才能得到结果。是否可以只循环一次并得到结果?


例如,我想将这个“\u201C”,“\u201D”替换为“\”“(智能双引号与标准双引号),并将“\u2018”,“\u2019”替换为“'”(智能单引号)带标准单引号)


public class HelloWorld{


     public static void main(String []args){

        List<String> toRemove = Arrays.asList("\u201C","\u201D");

        List<String> toRemove1 = Arrays.asList("\u2018","\u2019");

        String text = "KURT’X45T”YUZXC";

        text=toRemove.stream()

                .map(toRem -> (Function<String,String>) s ->  s.replaceAll(toRem, "\""))

                .reduce(Function.identity(), Function::andThen)

                .apply(text);


        System.out.println("---text--- "+ text);


        text=toRemove1.stream()

            .map(toRem -> (Function<String,String>) s ->  s.replaceAll(toRem, "'"))

            .reduce(Function.identity(), Function::andThen)

            .apply(text);


        System.out.println("---text-1-- "+ text);

     }

}



料青山看我应如是
浏览 69回答 1
1回答

浮云间

这可以使用map然后使用entrySet来解决,如下所示public class HelloWorld{&nbsp; &nbsp; &nbsp;public static void main(String []args){&nbsp; &nbsp; &nbsp; &nbsp; Map<String,String> map = new HashMap<String,String>();&nbsp; &nbsp; &nbsp; &nbsp; map.put("\u2018","'");&nbsp; &nbsp; &nbsp; &nbsp; map.put("\u2019","'");&nbsp; &nbsp; &nbsp; &nbsp; map.put("\u201C","\"");&nbsp; &nbsp; &nbsp; &nbsp; map.put("\u201D","\"");&nbsp; &nbsp; &nbsp; &nbsp; List<String> toRemove = Arrays.asList("\u2018","\u2019","\u201C","\u201D");&nbsp; &nbsp; &nbsp; &nbsp; String text = "KURT’X45T”YUZXC";&nbsp; &nbsp; &nbsp; &nbsp; text=map.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> (Function<String,String>) s ->&nbsp; s.replaceAll(e.getKey(), e.getValue()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .reduce(Function.identity(), Function::andThen)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .apply(text);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(text);&nbsp; &nbsp; &nbsp; &nbsp;// or you can even do like this&nbsp; &nbsp; &nbsp; &nbsp; text=map.entrySet().stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> (Function<String,String>) s ->&nbsp; s.replaceAll(e.getKey(), e.getValue()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .reduce(Function.identity(),(a, b) -> a.andThen(b))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .apply(text);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(text);&nbsp; &nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java