Languages
[Edit]
EN

Java 8 - convert char[] to Stream<Character>

6 points
Created by:
Flimzy
596

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

Merged questions

  1. Java 8 - create stream of Character objects from primitive char array
  2. How do I convert char[] to Stream<Character> in java?
  3. Java - convert primitive char array to stream of Character objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join