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
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.
2.1. Multiple Filters. The Stream API allows chaining multiple 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) .
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(" "));
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(" "));
.mapToObj(x-> {
String s = Integer.toBinaryString(x);
s = String.format("%8s", s).replaceAll(" ", "0");
return s;
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With