Can execute multiple statements with stream.mapToObj

Is it possible to execute several instructions in the mapToObj method? Suppose that I want to convert a character string to a Binary string using the code below:

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

But I want to process leading zeros using something like

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

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

+7
java-8 java-stream
source share
4 answers
 .mapToObj(x-> { String s = Integer.toBinaryString(x); s = String.format("%8s", s).replaceAll(" ", "0"); return s; }) 
+5
source share

Instead of replacing the space, you can use BigInteger and add “0” during the formatting step. This works because BigInteger considered 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 an easier solution that uses long instead of BigInteger , since the binary representation of Character.MAX_VALUE does not exceed the long limit.

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

You can call the .map() function after .mapToObject() , which will process binary strings, for example:

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

Of course you can. It does not even require a lambda expression with several statements.

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

All Articles