Reputation: 1032
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.
Upvotes: 28
Views: 119997
Reputation: 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);
Upvotes: 0
Reputation: 1
String myString = "xxx";
ArrayList<Character> myArrayList = myString.chars().mapToObj(x -> (char) x).collect(toCollection(ArrayList::new));
myArrayList.forEach(System.out::println);
Upvotes: 0
Reputation: 1330
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()
)
);
Upvotes: 7
Reputation: 4289
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
.
Upvotes: 7
Reputation: 29
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));
}
}
}
Upvotes: 0
Reputation: 33380
You need to add it like this.
String str = "abcd...";
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : str.toCharArray()) {
chars.add(c);
}
Upvotes: 21
Reputation: 2516
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);
}
Upvotes: 2
Reputation: 13890
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);
Upvotes: 5