28

How to convert a String without separator to an ArrayList<Character>.

My String is like this:

String str = "abcd..."

I know one way of doing this is converting the String to char[] first, and then convert the char [] to ArrayList <Character>.

Is there any better way to do this? like converting directly? Considering time and performance, because I am coding with a big database.

5
  • So...do you want to take the implicit string and convert each character in it to a collection of some sort? If that's the case, what have you tried? Some sample code would be beneficial. Commented Mar 11, 2013 at 5:18
  • Do you really want to convert to ArrayList or just wrap string into List backed by the original string? Commented Mar 11, 2013 at 5:18
  • @Makoto I have tried 'char [] chars = str.toCharArray (); ArrayList <Character> mylist = new ArrayList <Character> (); for (char c : chars) mylist.add (c);' Commented Mar 11, 2013 at 6:25
  • @MikhailVladimirov I really want to convert it to ArrayList Commented Mar 11, 2013 at 6:26
  • @squiguy As I mentioned below, your code seems not working. Commented Mar 11, 2013 at 6:27

8 Answers 8

21

You need to add it like this.

String str = "abcd...";
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : str.toCharArray()) {
  chars.add(c);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Well. I don't think it works. str.toCharArray () will return char [], while you are assigning it to an ArrayList with type Character. To be more precise, you cannot convert an array of primitives to an ArrayList like this.
This should work :), but as I mentioned, you converted the string to a char array first, and then added it one by one to get the ArrayList. I am considering the space and time costs while the string is very large and the number of strings is also huge in a database.
@aga_pan Hmm, well unless you venture off into some third party libraries, I am not sure there is a way around it. Beats me at least!
@aga_pan In the end, the efficiency of a loop to compiled byte code will be optimized by the virtual machine I am sure. The only way to find out would be to choose some methods and play around with it.
7

Sorry for the Retrobump, but this is now really easy!

You can do this easily in Java 8 using Streams! Try this:

String string = "testingString";
List<Character> list = string.chars().mapToObj((i) -> Character.valueOf((char)i)).collect(Collectors.toList());
System.out.println(list);

You need to use mapToObj because chars() returns an IntStream.

1 Comment

Error:(13, 114) java: incompatible types: inference variable R has incompatible bounds equality constraints: java.util.List<java.lang.Character> upper bounds: java.util.ArrayList<java.lang.Character>,java.lang.Object
7

use lambda expression to do this.

String big_data = "big-data";
ArrayList<Character> chars
        = new ArrayList<>(
                 big_data.chars()
                .mapToObj(e -> (char) e)
                .collect(
                        Collectors.toList()
                )
        );    

Comments

4

If you dn not need to modify list after it created, probably the better way would be to wrap string into class implementing List<Character> interface like this:

import java.util.AbstractList;
import java.util.List;

public class StringCharacterList extends AbstractList <Character>
{
    private final String string;

    public StringCharacterList (String string)
    {
        this.string = string;
    }

    @Override
    public Character get (int index)
    {
        return Character.valueOf (string.charAt (index));
    }

    @Override
    public int size ()
    {
        return string.length ();
    }
}

And then use this class like this:

List <Character> l = new StringCharacterList ("Hello, World!");
System.out.println (l);

1 Comment

Thanks, but what I need is an ArrayList :)
2
public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "abcd...";
        ArrayList<Character> a=new ArrayList<Character>();
        for(int i=0;i<str.length();i++)
        {
            a.add(str.charAt(i));

        }
        System.out.println(a);
    }

Comments

0

you can do it like this:

import java.util.ArrayList;

public class YourClass{

    public static void main(String [] args){

        ArrayList<Character> char = new ArrayList<Character>();
        String str = "abcd...";

        for (int x = 0; x < str.length(); x ++){
            char.add(str.charAt(x));
        }
    }
}

Comments

0
String myString = "xxx";
ArrayList<Character> myArrayList = myString.chars().mapToObj(x -> (char) x).collect(toCollection(ArrayList::new));
myArrayList.forEach(System.out::println);

Comments

-1
String str="GuruPrasadyadav";
         List<Character> list = new ArrayList<>(); 
         for (int i = 0; i < str.length(); i++) { 
             list.add(str.charAt(i));
             } System.out.println(list); Set<Character>
          charSet = new HashSet<Character>(list);
             System.out.println(charSet);
         

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.