0

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?

2 Answers 2

1

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) );
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.