Reputation: 33
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".
Upvotes: 2
Views: 346
Reputation: 298389
This is surely not a task for the Stream API. If you still want to do this but minimize the loss of readability and performance, you may use something like
String s1 = IntStream.range(0, 10)
.map(i -> i<s.length()? s.charAt(i): '0')
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
A straight-forward approach would be
int cap = Math.min(s.length(), 10);
String s1 = s.substring(0, cap)+"0000000000".substring(cap);
or
int cap = Math.min(s.length(), 10);
String s1=new StringBuilder(10).append(s, 0, cap).append("0000000000", cap, 10).toString();
Upvotes: 4
Reputation: 3134
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"));
Upvotes: 1
Reputation: 2773
If you have Java 11 you can use a new String.repeat
method.
Just find how much zeros you need int n = 10 - s.length();
and then add it s1 = s + "0".repeat(n);
In Java 8 you can generate zeros with streams
String zeros = Stream.generate(() -> "0").limit(n).collect(Collectors.joining());
s1 = s + zeros
Upvotes: 0