Reputation: 23
I have a list of Unicode characters that need to be replaced by some other characters I have got it working. But, I have to loop this twice to get the result. Is it possible to loop only once and get the result?
For example, I want to replace this "\u201C","\u201D" with "\"" (smart double quote with standard double quote) and replace "\u2018","\u2019" with "'" (smart single quote with standard single quote)
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);
}
}
Upvotes: 2
Views: 168
Reputation: 2355
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);
}
}
Upvotes: 2