Thursday, October 19, 2017

URLify in java 8 style functional flavor

 Write a method to replace all spaces in a string with '%20'

Instead of using str.replaceAll("\\s", "%20"), here is a function. This exercise is to help learning.

public String URLifyJava8(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.flatMap(c -> Character.isWhitespace(c)
? "%20".chars().mapToObj(ch -> (char) ch) : Stream.of(c))
.of(StringBuilder::new, StringBuilder::append,
(r1, r2) -> {
return r1;
StringBuilder::toString, Collector.Characteristics.CONCURRENT));

No comments:

Post a Comment