为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

料青山看我应如是 2023-10-19 21:14:59
我有一个 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);     }}
查看完整描述

1 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

这可以使用map然后使用entrySet来解决,如下所示

public class HelloWorld{


     public static void main(String []args){

        Map<String,String> map = new HashMap<String,String>();

        map.put("\u2018","'");

        map.put("\u2019","'");

        map.put("\u201C","\"");

        map.put("\u201D","\"");




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


        String text = "KURT’X45T”YUZXC";



        text=map.entrySet().stream()

                .map(e -> (Function<String,String>) s ->  s.replaceAll(e.getKey(), e.getValue()))

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

                .apply(text);

        System.out.println(text);


       // or you can even do like this


        text=map.entrySet().stream()

                .map(e -> (Function<String,String>) s ->  s.replaceAll(e.getKey(), e.getValue()))

                .reduce(Function.identity(),(a, b) -> a.andThen(b))

                .apply(text);

        System.out.println(text);



     }

}


查看完整回答
反对 回复 2023-10-19
  • 1 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信