EN
Java 8 - convert char[] to Stream<Character>
6
points
Short solution:
char[] charArr = {'a', 'b', 'c'};
// Example 1 - the best way:
Stream<Character> charStream = new String(charArr)
.chars().mapToObj(c -> (char) c);
Short solution - another 2 approaches:
char[] charArr = {'a', 'b', 'c'};
// Example 2
Stream<Character> charStream2 = IntStream.range(0, charArr.length)
.mapToObj(idx -> charArr[idx]);
// Example 3
Stream<Character> charStream3 = CharBuffer.wrap(charArr)
.chars().mapToObj(i -> (char) i);
In this post we can find 3 different ways of how to create stream of Characters from primitive char[] array in java.
Code snipped with the best way of how to do it:
Below we have full code snipped with those solutions.
1. String.chars()
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example1 {
public static void main(String[] args) {
char[] charArr = {'a', 'b', 'c'};
Stream<Character> charStream = new String(charArr)
.chars().mapToObj(c -> (char) c);
String string = charStream.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(string); // abc
}
}
Output:
abc
2. IntStream.range()
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Example2 {
public static void main(String[] args) {
char[] charArr = {'a', 'b', 'c'};
Stream<Character> charStream = IntStream.range(0, charArr.length)
.mapToObj(idx -> charArr[idx]);
String string = charStream.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(string); // abc
}
}
Output:
abc
3. CharBuffer.wrap().chars()
import java.nio.CharBuffer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example3 {
public static void main(String[] args) {
char[] charArr = {'a', 'b', 'c'};
Stream<Character> charStream = CharBuffer.wrap(charArr)
.chars().mapToObj(i -> (char) i);
String string = charStream.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(string); // abc
}
}
Output:
abc