FSm
FSm

Reputation: 2057

Can do multiple statements with stream.mapToObj

Is it possible to do multiple statements in mapToObj method? . Let say I want to convert a String of characters to a String of binary using the below code:

 String str = "hello";
 String bin = str.chars()
                  .mapToObj(x-> Integer.toBinaryString(x))
                  .collect(Collectors.joining(" "));

But, I want to handle the leading zeros using something like

String.format("%8s", x).replaceAll(" ", "0")

So, how to add it in mapToObj method. I am very new to Java 8 features. Any help would be appreciated

Upvotes: 9

Views: 3070

Answers (4)

Flown
Flown

Reputation: 11740

Instead of replacing the space padding you could use BigInteger and prepend a '0' during the format step. This works because BigInteger is treated as integral.

String bin = str.chars()
        .mapToObj(Integer::toBinaryString)
        .map(BigInteger::new)
        .map(x -> String.format("%08d", x))
        .collect(Collectors.joining(" "));

EDIT

As @Holger suggested there is a more lightweight solution using long instead of BigInteger, since the binary representation of Character.MAX_VALUE does not exceed the limit of long.

String bin = str.chars()
        .mapToObj(Integer::toBinaryString)
        .mapToLong(Long::parseLong)
        .mapToObj(l -> String.format("%08d", l))
        .collect(Collectors.joining(" "));

Upvotes: 6

Eran
Eran

Reputation: 393791

Of course you can. It doesn't even require a lambda expression with multiple statements.

String bin = str.chars()
                .mapToObj(x-> String.format("%8s", Integer.toBinaryString(x)).replaceAll(" ", "0"))
                .collect(Collectors.joining(" "));

Upvotes: 3

Eugene
Eugene

Reputation: 120848

.mapToObj(x-> {
    String s = Integer.toBinaryString(x);
    s = String.format("%8s", s).replaceAll(" ", "0");
    return s;
 })

Upvotes: 6

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

You can call .map() function after .mapToObject() that will process binary strings, e.g.:

String str = "hello";
String bin = str.chars()
              .mapToObj(x-> Integer.toBinaryString(x))
              .map(str -> String.format("%8s", str).replaceAll(" ", "0"))
              .collect(Collectors.joining(" "));

Upvotes: 3

Related Questions