Explain Codes LogoExplain Codes Logo

How to convert a String to CharSequence?

java
java-8
generics
type-casts
Nikita BarsukovbyNikita Barsukov·Feb 15, 2025
TLDR

Any String in Java gracefully fits into the CharSequence interface, because String is like a diligent student who implements all that CharSequence commands. Have a String? Just put it in the place where a CharSequence is called into action:

String str = "Example"; // Yes, a simple example! CharSequence charSeq = str; // No fuss, no hassle!

This is universal, like the law of gravity — all String instances are fast friends with CharSequence.

Strings and their alter egos

Whenever a String transforms into a CharSequence, it carries along its own unique skillset, some of which is not shared by all CharSequence. For instance, String instances are immutable like diamonds, whereas the StringBuilder or StringBuffer are mutable CharSequences, designed for evolution after birth.

Swap faces between CharSequence implementations:

CharSequence charSeqMutable = new StringBuilder(str); // Mutable version of str String ripVanWinkle = charSeqMutable.toString(); // Wakes up as a String

The .toString() method being the potion that allows every CharSequence to magically don a String costume whenever needed.

Arrays and Collections: Unusual Suspects

From Arrays to List

Feel like your array needs a list's flexibility? Just wrap it with Arrays.asList(). This transforms your array into a list while keeping its String inhabitants intact. Voila, you’ve got a List<CharSequence>.

Stream API: Collection’s BFF

Stuck with a List<String> and you want a List<CharSequence>? Wave Java 8's stream() wand:

List<String> stringList = Arrays.asList("apple", "banana", "cherry"); // Just a fruit basket, nothing more! List<CharSequence> charSeqList = stringList.stream() .collect(Collectors.toList()); // Now, it's a boxed fruit basket!

Zero angst, zero drama. It's as simple as changing one's spectacles. Thanks to Java's polymorphism!

Before you trip over

A word of caution though, a List<String> is like a cat, ie. not directly assignable to List<CharSequence>. Different species, folks!

Strings to CharSequence: Unnoticed Pitfalls

No Pain, Only Gain

Whenever hopping from a String to a CharSequence, you're safe. However, always check for potential data or behavior quirks while hopping backwards. Your clone might lose a limb!

Choose Compatibility, Choose Peace

CharSequence is like the friendly neighbourhood Spiderman, getting along with any kind of character sequences in Java.

Generics, Subtypes, and Type Casts

Generics and CharSequence: A match made in Java heaven

When dealing with generics, CharSequence can sometimes play hard-to-get. List<CharSequence> accepts Strings, but assigning List<String> to List<CharSequence> is a game it won't play.

Wildcards to the rescue

To make peace with generics and CharSequence, wildcards are your best bet:

List<? extends CharSequence> charSeqList = new ArrayList<String>(); // Checkmate problems, wildcards wins

Stream API: the subtle dance

And if you're grooving with the Stream API, be careful with your collector selections:

List<CharSequence> collectedCharSeqs = stringStream .collect(Collectors.toCollection(ArrayList::new)); // Collectors enters the game, ArrayList rejoices

Be smart, skip awkward type mismatches between collections of String and CharSequence.