【问题标题】:Java8 streams how to replace a particular list of character with some other list of charactersJava8流如何用一些其他字符列表替换特定的字符列表
【发布时间】:2019-10-13 14:45:11
【问题描述】:

我有一个 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);
     }
}

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:
    • 这可以使用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);
    
    
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多