Converting stream of int's to char's in java
If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String
constructor and provide a Charset
, or use InputStreamReader
with the appropriate Charset
instead.
Simply casting from int
to char
only works if you want ISO-8859-1, if you're reading bytes from a stream directly.
EDIT: If you are already using a Reader
, then casting the return value of read()
to char
is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int)
to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.
How to convert IntStream into ListCharacter?
You may map each int
to a char
then collect into a list, this will result in a list of character given by their ASCII code
List<Character> r = IntStream.range(50, 80).mapToObj(a -> (char) a).collect(Collectors.toList());
System.out.println(r); // [2, 3, 4, 5, 6, 7, 8, 9, :, ;, <, =, >, ?, @, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
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.
Convert a String to a java.util.StreamCharacter
You can use chars()
method provided in CharSequence
and since String
class implements this interface you can access it.
The chars()
method returns an IntStream
, so you need to cast it to (char)
if you will like to convert IntStream
to Stream<Character>
E.g.
public class Foo {
public static void main(String[] args) {
String x = "new";
Stream<Character> characters = x.chars().mapToObj(i -> (char) i);
characters.forEach(System.out::println);
}
}
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);
}
Why is String.chars() a stream of ints in Java 8?
As others have already mentioned, the design decision behind this was to prevent the explosion of methods and classes.
Still, personally I think this was a very bad decision, and there should, given they do not want to make CharStream
, which is reasonable, different methods instead of chars()
, I would think of:
Stream<Character> chars()
, that gives a stream of boxes characters, which will have some light performance penalty.IntStream unboxedChars()
, which would to be used for performance code.
However, instead of focusing on why it is done this way currently, I think this answer should focus on showing a way to do it with the API that we have gotten with Java 8.
In Java 7 I would have done it like this:
for (int i = 0; i < hello.length(); i++) {
System.out.println(hello.charAt(i));
}
And I think a reasonable method to do it in Java 8 is the following:
hello.chars()
.mapToObj(i -> (char)i)
.forEach(System.out::println);
Here I obtain an IntStream
and map it to an object via the lambda i -> (char)i
, this will automatically box it into a Stream<Character>
, and then we can do what we want, and still use method references as a plus.
Be aware though that you must do mapToObj
, if you forget and use map
, then nothing will complain, but you will still end up with an IntStream
, and you might be left off wondering why it prints the integer values instead of the strings representing the characters.
Other ugly alternatives for Java 8:
By remaining in an IntStream
and wanting to print them ultimately, you cannot use method references anymore for printing:
hello.chars()
.forEach(i -> System.out.println((char)i));
Moreover, using method references to your own method do not work anymore! Consider the following:
private void print(char c) {
System.out.println(c);
}
and then
hello.chars()
.forEach(this::print);
This will give a compile error, as there possibly is a lossy conversion.
Conclusion:
The API was designed this way because of not wanting to add CharStream
, I personally think that the method should return a Stream<Character>
, and the workaround currently is to use mapToObj(i -> (char)i)
on an IntStream
to be able to work properly with them.
Related Topics
Use of '? Extends ' and '? Super ' in Collection Generics
How to Serve Jsps from Inside a Jar in Lib, or Is There a Workaround
How to Restrict Jfilechooser to a Directory
Is There a Good Reason to Use "Printf" Instead of "Print" in Java
Difference Between "On-Heap" and "Off-Heap"
How to Stop Selenium from Creating Temporary Firefox Profiles Using Web Driver
What Does the Colon (:) Operator Do
Error:Java: Invalid Source Release: 8 in Intellij. What Does It Mean
Build Project into a Jar Automatically in Eclipse
This: Cannot Use This in Static Context
Can Anyone Recommend a Simple Java Web-App Framework
What Is the Default Max Heap Size (-Xmx) in Java 8
Writing a Large Resultset to an Excel File Using Poi
Why Do We Need Interfaces in Java
How to Get Whole and Fractional Parts from Double in Jsp/Java