Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to print an `IntStream` as a `String`

With Java-8 I can easily treat a String (or any CharSequence) as an IntStream using either the chars or the codePoints method.

IntStream chars = "Hello world.".codePoints(); 

I can then manipulate the contents of the stream

IntStream stars = chars.map(c -> c == ' ' ? ' ': '*'); 

I have been hunting for a tidy way to print the results and I cant even find a simple way. How do I put this stream of ints back into a form that can be printed like I can a String.

From the above stars I hope to print

***** ****** 
like image 993
OldCurmudgeon Avatar asked Nov 28 '13 12:11

OldCurmudgeon


People also ask

How does IntStream range () work?

range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream. range(1,5) generates a stream of ' 1,2,3,4 ' of type int .

What is IntStream rangeClosed?

IntStream rangeClosed() method in Java The rangeClosed() class in the IntStream class returns a sequential ordered IntStream from startInclusive to endInclusive by an incremental step of 1. This includes both the startInclusive and endInclusive values.

What does IntStream return?

IntStream of(int… values) returns a sequential ordered stream whose elements are the specified values. Parameters : IntStream : A sequence of primitive int-valued elements.


1 Answers

String result = "Hello world."   .codePoints() //.parallel()  // uncomment this line for large strings   .map(c -> c == ' ' ? ' ': '*')   .collect(StringBuilder::new,            StringBuilder::appendCodePoint, StringBuilder::append)   .toString(); 

But still, "Hello world.".replaceAll("[^ ]", "*") is simpler. Not everything benefits from lambdas.

like image 137
Holger Avatar answered Oct 10 '22 19:10

Holger