String manipulation in Java8

Johan :

I have written some code in Java7 to manipulate a String. If the string size is >= 10 it will return a substring of size 10 but if the size is < 10 it will append 0s in the string. I wonder if there is a way to write the same code in Java8 using streams and lambdas.

There are some question related to String manipulation in Java8 but none of them are helpful to my problem.

String s = "12345678";
String s1 = s;

if(s.length() >= 10) {
     s1 = s1.substring(0,10);
}
else {
     for (int k = s.length() ; k < 10 ; k++) {
         s1 = s1 + "0";
     }
}

I expect the output string "1234567800".

Adrian :

you can combine Stream::generate, Collectors::collectingAndThen and Collectors::joining to obtain a one line solution, though it isn't better than these ones

public static String padd10(String str) {
    return Stream.generate(() -> "0")
            .limit(str.length() >= 10 ? 0 : 10 - str.length())
            .collect(Collectors.collectingAndThen(
              Collectors.joining(), str.substring(0, Math.min(str.length(), 10))::concat));
}

and call it

System.out.println(padd10("123"));
System.out.println(padd10("1234567800"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117438&siteId=1