Given a String, the task is to convert it into a List of Characters in Java.
Examples:
Input: String = "Geeks"
Output: [G, e, e, k, s]
Input: String = "GeeksForGeeks"
Output: [G, e, e, k, s, F, o, r, G, e, e, k, s]
Below are the various ways to do so:
- Naive Method
Approach:
- Get the String.
- Create an empty List of Characters.
- Add each character of String to the List.
- Return the List.
Below is the implementation of the above approach:
import java.util.*;
class GFG {
public static List<Character>
convertStringToCharList(String str)
{
List<Character> chars = new ArrayList<>();
for ( char ch : str.toCharArray()) {
chars.add(ch);
}
return chars;
}
public static void main(String[] args)
{
String str = "Geek" ;
List<Character>
chars = convertStringToCharList(str);
System.out.println(chars);
}
}
|
- Using Java 8 Stream:
Approach:
- Get the String.
- Create a List of Characters.
- Convert to String to IntStream using chars() method.
- Convert IntStream to Stream using mapToObj() method.
- Collect the elements as a List Of Characters using collect()
- Return the List.
Below is the implementation of the above approach:
import java.util.*;
import java.util.stream.Collectors;
class GFG {
public static List<Character>
convertStringToCharList(String str)
{
List<Character> chars = str
.chars()
.mapToObj(e -> ( char )e)
.collect(Collectors.toList());
return chars;
}
public static void main(String[] args)
{
String str = "Geek" ;
List<Character>
chars = convertStringToCharList(str);
System.out.println(chars);
}
}
|
- Using Java 8 Stream:
Approach:
- Get the String.
- Use the AbstractList interface to convert the String into List of Character
- Return the List.
Below is the implementation of the above approach:
import java.util.*;
class GFG {
public static List<Character>
convertStringToCharList(String str)
{
return new AbstractList<Character>() {
@Override
public Character get( int index)
{
return str.charAt(index);
}
@Override
public int size()
{
return str.length();
}
};
}
public static void main(String[] args)
{
String str = "Geek" ;
List<Character>
chars = convertStringToCharList(str);
System.out.println(chars);
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Dec, 2018
Like Article
Save Article