EN
Java 8 - convert char[] to Stream<Character>
6 points
Short solution:
xxxxxxxxxx
1
char[] charArr = {'a', 'b', 'c'};
2
3
// Example 1 - the best way:
4
Stream<Character> charStream = new String(charArr)
5
.chars().mapToObj(c -> (char) c);
Short solution - another 2 approaches:
xxxxxxxxxx
1
char[] charArr = {'a', 'b', 'c'};
2
3
// Example 2
4
Stream<Character> charStream2 = IntStream.range(0, charArr.length)
5
.mapToObj(idx -> charArr[idx]);
6
7
// Example 3
8
Stream<Character> charStream3 = CharBuffer.wrap(charArr)
9
.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.
xxxxxxxxxx
1
import java.util.stream.Collectors;
2
import java.util.stream.Stream;
3
4
public class Example1 {
5
6
public static void main(String[] args) {
7
8
char[] charArr = {'a', 'b', 'c'};
9
10
Stream<Character> charStream = new String(charArr)
11
.chars().mapToObj(c -> (char) c);
12
13
String string = charStream.map(String::valueOf)
14
.collect(Collectors.joining());
15
16
System.out.println(string); // abc
17
}
18
}
Output:
xxxxxxxxxx
1
abc
xxxxxxxxxx
1
import java.util.stream.Collectors;
2
import java.util.stream.IntStream;
3
import java.util.stream.Stream;
4
5
public class Example2 {
6
7
public static void main(String[] args) {
8
9
char[] charArr = {'a', 'b', 'c'};
10
11
Stream<Character> charStream = IntStream.range(0, charArr.length)
12
.mapToObj(idx -> charArr[idx]);
13
14
String string = charStream.map(String::valueOf)
15
.collect(Collectors.joining());
16
17
System.out.println(string); // abc
18
}
19
}
Output:
xxxxxxxxxx
1
abc
xxxxxxxxxx
1
import java.nio.CharBuffer;
2
import java.util.stream.Collectors;
3
import java.util.stream.Stream;
4
5
public class Example3 {
6
7
public static void main(String[] args) {
8
9
char[] charArr = {'a', 'b', 'c'};
10
11
Stream<Character> charStream = CharBuffer.wrap(charArr)
12
.chars().mapToObj(i -> (char) i);
13
14
String string = charStream.map(String::valueOf)
15
.collect(Collectors.joining());
16
17
System.out.println(string); // abc
18
}
19
}
Output:
xxxxxxxxxx
1
abc