1

It should be simple but I couldn't find the easy one line answer. How can I change CharSequence[] to String[]. My goal is to change CharSequnce[]={"a","b","c"} to List<String>, but when I write Arrays.asList(a) android studio gives an error saying that Required type is List<String> but the Provided is List<CharSequence>. So it seems I need to change CharSequence array to String array first.

I also tried Arrays.asList(Arrays.toString(e)) but the output of printing the List will be [[a, ,b, c]], which is not what I want.

3
  • 4
    Notice that CharSequence[]={"a", "b", "c"} is assigning a right-hand String[] to CharSequence[], which begs the question: why are you using CharSequence to begin with? You could of course map these things: Arrays.stream(a).map(Object::toString).toList(), but that's seemingly wasteful compared to fixing your stored data to begin with. Commented Apr 3, 2024 at 15:03
  • Do you understand that a String is a CharSequence? The String class implements the CharSequence interface. Commented Apr 3, 2024 at 16:17
  • @Rogue Thanks for your answer. This was just an example. I am using a CharSequence in this context (to get entries from a custom spinner): TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MultiSpinner); CharSequence[] entries = a.getTextArray(R.styleable.MultiSpinner_android_entries); Commented Apr 4, 2024 at 9:01

1 Answer 1

4

Iterate the array, transform each element to string, add transformed element to resulting list. You can use the Stream API (just one option):

CharSequence[] charSeqArr = //get data
List<String> result = Stream.of(charSeqArr)
            .map(CharSequence::toString)
            .toList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. The only problem with this is that Android Studio requires API >= 34.

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.