2

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".

GBlodgett
  • 12,612
  • 4
  • 26
  • 42
Johan
  • 33
  • 2

3 Answers3

4

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();
Holger
  • 243,335
  • 30
  • 362
  • 661
1

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"));
Adrian
  • 2,438
  • 7
  • 23
0

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
dehasi
  • 2,014
  • 16
  • 23
  • I suspect it is a replacement of else block as it will generate a string of 0s and concatenate it with string s. Is there any way to omit if else block ? – Johan Apr 01 '19 at 13:29