Baurzhan Kozhaev
Baurzhan Kozhaev

Reputation: 123

How to convert ArrayList of Strings to char array

The following code converts ArrayList<String> to char[] and print output which appears as [back, pack]. Here, the char[] includes ',' and ' '. Is there a way to do it in another way to get rid of comma and space?

ArrayList<String> list = new ArrayList<String>();
list.add("back");
list.add("pack");

char[] chars = list.toString().toCharArray();

for (char i : chars){
   System.out.print(i);
}

Upvotes: 2

Views: 25108

Answers (5)

hotkey
hotkey

Reputation: 147951

You can do it by joining the Strings in your ArrayList<String> and then getting char[] from the result:

char[] chars = list.stream().collect(Collectors.joining()).toCharArray();

Here .stream.collect(Collectors.joining()) part is Java 8 Stream way to join a sequence of Strings into one. See: Collectors.joining() docs.

If you want any delimiter between the parts in the result, use Collectors.joining(delimiter) instead.

There's also an overload which adds prefix and suffix to the result, for example, if you want [ and ] in it, use Collectors.joining("", "[", "]").

Upvotes: 4

mohammedkhan
mohammedkhan

Reputation: 975

Your toString method on list is what is adding the comma and space, it's a String representation of your list. As list is a collection of Strings you don't need to call toString on it, just iterate through the collection converting each String into an array of chars using toCharArray (I assume you will probably want to add all the chars of all the Strings together).

Upvotes: 2

bodo
bodo

Reputation: 847

Just an example how should you resolved large list to array copy. Beware number of characters must be less then Integer.MAX. This code is just an example how it could be done. There are plenty of checks that one must implement it to make that code works properly.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class WrappedList {

    //Or replace with some better counter
    int totalCharCount = 0;
    final List<String> list;

    public WrappedList() {
        this(new ArrayList<String>());
    }

    public WrappedList(final List<String> list) {
        this.list = list;
    }

    public void add(final String toAdd) {
        if(toAdd != null) {
            totalCharCount += toAdd.length();
            this.list.add(toAdd);
        }
    }

    public List<String> getList() {
        return Collections.unmodifiableList(list);
    }

    public char[] toCharArray() {
        return this.toCharArray(this.totalCharCount);
    }


    public char[] toCharArray(final int charCountToCopy) {
        final char[] product = new char[charCountToCopy];
        int buffered = 0;
        for (String string : list) {
            char[] charArray = string.toCharArray();
            System.arraycopy(charArray, 0, product, buffered, charArray.length);
            buffered += charArray.length;
        }
        return product;
    }

    //Utility method could be used  also as stand-alone class
    public char[] toCharArray(final List<String> all) {
        int size = all.size();
        char[][] cpy = new char[size][];
        for (int i = 0; i < all.size(); i++) {
            cpy[i] = all.get(i).toCharArray();
        }
        int total = 0;
        for (char[] cs : cpy) {
            total += cs.length;
        }
        return this.toCharArray(total);
    }

    public static void main(String[] args) {
        //Add String iteratively
        WrappedList wrappedList = new WrappedList();
        wrappedList.add("back");
        wrappedList.add("pack");
        wrappedList.add("back1");
        wrappedList.add("pack1");
        final char[] charArray = wrappedList.toCharArray();
        System.out.println("Your char array:");
        for (char c : charArray) {
            System.out.println(c);
        }

        //Utility method one time for all, should by used in stand-alone Utility class
        System.out.println("As util method");
        System.out.println(wrappedList.toCharArray(wrappedList.getList()));
    }

}

See also: system-arraycopy-than-a-for-loop-for-copying-arrays

Upvotes: 0

Anand Pandey
Anand Pandey

Reputation: 393

String to charArray in Java Code:

ArrayList<String> list = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
list.add( "back" );
list.add( "pack" );
for ( String string : list )
{
    for ( char c : string.toCharArray() )
    {
        chars.add( c );
    }
}
System.out.println( chars );

Upvotes: 2

Shomil Khare
Shomil Khare

Reputation: 91

Just replace the this line

char[] chars = list.toString().toCharArray();

with below two lines

String str=list.toString().replaceAll(",", "");
char[] chars = str.substring(1, str.length()-1).replaceAll(" ", "").toCharArray();

Upvotes: 4

Related Questions