Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 340
FSm Avatar asked Jan 15 '18 12:01

FSm


People also ask

How do you do multiple operations on a Stream?

The correct approach would be to use . map() which, like the name says, maps one value to another. In your case the first operation you want to do is to map a Person to a JSONObject. The second operation is a reducer function where you want to reduce all JSONObjects to one JSONArray object.

Can we have multiple filter in Stream?

2.1. Multiple Filters. The Stream API allows chaining multiple filters.

Can Java 8 have 2 filters?

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x. isCool()) by filter(ItemType::isCool) .


2 Answers

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(" "));
like image 193
Flown Avatar answered Oct 19 '22 21:10

Flown


.mapToObj(x-> {
    String s = Integer.toBinaryString(x);
    s = String.format("%8s", s).replaceAll(" ", "0");
    return s;
 })
like image 45
Eugene Avatar answered Oct 19 '22 19:10

Eugene