Jay Cutler
Jay Cutler

Reputation: 7

How to convert contents of String ArrayList to char ArrayList

I currently have a String ArrayList with the contents [a, b, c, d, e...] and so forth. However, I need to have a character based arraylist (ArrayList name). How would I go upon looping through my String arraylist and converting its elements to char, to append to the char arraylist?

The same goes for converting a string arraylist full of numbers [1,2,3,4...] to an integer arraylist. How would I go upon looping through, converting the type, and adding it to the new arraylist?

Upvotes: 0

Views: 1083

Answers (2)

Mureinik
Mureinik

Reputation: 312219

As you said - you have to loop over the ArrayList:

List<String> stringList = ...;
List<Character> charList = new ArrayList<>(old.size());

// assuming all the strings in old have one character, 
// as per the example in the question 
for (String s : stringList) {
    charList.add(s.charAt(0));
}

EDIT:
You did not specify which java version you're using, but in Java 8 this can be done much more elegantly using the stream() method:

List<Character> charList = 
    stringList.stream().map(s -> s.charAt(0)).collect(Collectors.toList());

Upvotes: 0

lcjury
lcjury

Reputation: 1258

For the first problem just loop using a for and use the char charAt(0) method of string

List<String> arrayList;
List<Character> newArrayList = new ArrayList<>();

for( int i = 0; i < arrayList.size(); i++ ){
    String string = arrayList.at(i);
    newArrayList.add( string.charAt(0) ); // 0 becouse each string have only 1 char
}

for the second you can use Intenger.parseint

List<String> arrayList;
List<int> newArrayList = new ArrayList<>();

for( int i = 0; i < arrayList.size(); i++ )
{
    String string = arrayList.at(i);
    newArrayList.add( Intenget.parseInt(string) );
}

Upvotes: 1

Related Questions