亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號