Reputation: 2057
Simply, the code below produces a stream of five lines, I need to concat these lines into one line (while streaming) for further use and before collecting them.The code is about to convert a character string into one long binary string
Stream<String> binText = "hello".chars()
.mapToObj(x-> Integer.toBinaryString(x))
.map(x-> String.format("%8s", x).replaceAll(" ", "0"));
I'm a bit new for the term of "Stream API", so any suggestion would be appreciated.
Update: Let say I want map the stream from the above code into int []
of 0
and 1
, actually, I tried the below code and it works fine but it seems not efficient and need to be normalized
int [] binText = "hello".chars()
.mapToObj(x-> Integer.toBinaryString(x))
.map(x-> String.format("%8s", x).replaceAll(" ", "0"))
.flatMap(s-> Stream.of(s.split("")))
.mapToInt(Integer::parseInt)
.toArray();
isn't it ?
Upvotes: 1
Views: 98
Reputation: 31878
What you are looking for is a collector to join those strings and you would have
.collect(Collectors.joining())
eventually the complete solution could be:
String binText = "hello".chars()
.mapToObj(Integer::toBinaryString)
.map(x-> String.format("%8s", x).replace(" ", "0"))
.collect(Collectors.joining());
Upvotes: 1