convert string to arraylist <Character> in java

三世轮回 提交于 2019-11-29 03:14:46

You need to add it like this.

String str = "abcd...";
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : str.toCharArray()) {
  chars.add(c);
}

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()
                )
        );    

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.

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);
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);
    }

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));
        }
    }
}

There is one-line guava solution:

Lists.charactersOf("hello");

You can pass resulting ImmutableList to constructor of ArrayList but may I ask why do you need exactly ArrayList?

String myString = "xxx";
ArrayList<Character> myArrayList = myString.chars().mapToObj(x -> (char) x).collect(toCollection(ArrayList::new));
myArrayList.forEach(System.out::println);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!