Simplest way to print an `IntStream` as a `String`
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.
Java 8 Streams: IntStream to String
You can use toArray()
, then the String(int[], int, int)
constructor. This isn't entirely satisfactory as chars()
is specified to return UTF-16 code units, basically:
Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted.
Using codePoints()
instead would be more in-keeping with this constructor, which expects code points rather than UTF-16 code units. Otherwise (with chars
) if your original string does contain surrogate pairs, you may find you get an error - I haven't tried it, but it would make sense.
I don't know of a simple way of doing this without converting to an array first.
Concat different Streams and print on Java
I'm trying to print a concat Stream that includes String and Integer elements
Wrong, IntStream is a specific stream of primitive int
value(s), and it is not the same as Stream, and therefore, IntStream::boxed
or IntStream::mapToObj
must be invoked to produce Stream<?>
which can be used in Stream::concat
:
Stream<?> many = Stream
.concat(part1, Stream
.concat(part2, Stream
.concat(part3, Stream
.concat(part4, Stream
.concat(part5.boxed(), part6)
)
)
)
);
To get the result of the string concatenation as String, a terminal operation `Stream.collect(Collectors.joining())` should be applied after mapping all the objects in the streams into String using `String::valueOf` (or `Objects::toString`):
```java
String result = many.map(String::valueOf).collect(Collectors.joining());
System.out.println(result);
// -> Testing the streams concat on Java, dividing this phrase in 6 parts.
However, such verbose Stream concatenation is redundant, and the Stream
s can be joined using Stream.of + Stream::flatMap
. In the example below, IntStream
mapped to String immediately, so no extra Stream::map
is needed:
Stream<String> many = Stream
.of(part1, part2, part3, part4, part5.mapToObj(String::valueOf), part6)
.flatMap(s -> s);
String res = many.collect(Collectors.joining());
System.out.println(res);
// -> Testing the streams concat on Java, dividing this phrase in 6 parts.
What's the simplest way to print a Java array?
Since Java 5 you can use Arrays.toString(arr)
or Arrays.deepToString(arr)
for arrays within arrays. Note that the Object[]
version calls .toString()
on each object in the array. The output is even decorated in the exact way you're asking.
Examples:
Simple Array:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));Output:
[John, Mary, Bob]
Nested Array:
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
// Gives undesired output:
System.out.println(Arrays.toString(deepArray));
// Gives the desired output:
System.out.println(Arrays.deepToString(deepArray));Output:
[[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
[[John, Mary], [Alice, Bob]]double
Array:double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));Output:
[7, 9, 5, 1, 3 ]
How to convert Stream of Characters into a String in Java 8
Refer to @jubobs solution link. That is, you could do it this way in your case:
Stream<Character> testStream = Stream.of('a', 'b', 'c');
String result = testStream.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
This is more performant then map/cast
ping each character to a String
first and then joining
, as StringBuilder#append(char c)
will cut out that intermediate step.
How to convert a stream of Character into array of Character using stream functions in java
static public void reverseString(char[] s) {
Character[] upperCaseArray = IntStream.range(0, s.length)
.mapToObj(index -> s[index])
.map(Character::toUpperCase)
.toArray(Character[]::new);
}
java stream 8, every sixth word print in new line
Split the list into chunks of 5 and join the items inside each chunk.
IntStream.iterate(0, i -> i < list.size(), i -> i + 5)
.forEach(i -> System.out.println(
IntStream.range(i, Math.min(i + 5, list.size()))
.mapToObj(list::get)
.map(s -> s + "(" + s.length() + ")")
.collect(Collectors.joining("; "))
));
Note: Stream.iterate
with condition is available in Java 9.
Pure Java 8 solution could use Stream.limit
with a calculated number of chunks:
IntStream.iterate(0, i -> i + 5)
.limit(list.size() / 5 + (list.size() % 5 > 0 ? 1 : 0))
.forEach(i -> System.out.println(
IntStream.range(i, Math.min(i + 5, list.size()))
.mapToObj(list::get)
.map(s -> s + "(" + s.length() + ")")
.collect(Collectors.joining("; "))
));
Related Topics
Read Error Response Body in Java
Fastest Way to Iterate an Array in Java: Loop Variable VS Enhanced for Statement
Pass Data from Java Servlet to Jsp
Write a Program That Will Surely Go into Deadlock
How to Send Data to Com Port Using Java
Howto Get Rid of <Mvc:Annotation-Driven />
Display Numbers from 1 to 100 Without Loops or Conditions
Differencebetween Canonical Name, Simple Name and Class Name in Java Class
JPA How to Make Composite Foreign Key Part of Composite Primary Key
What in the World Are Spring Beans
How to Convert Iterable to Collection
How to Set a Long Java Classpath in Windows
Download Large File from Server Using Rest Template Java Spring MVC