Convert a String to a List of Characters in Java
In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.
Example:
In this example, we will use the toCharArray()
method to convert a String into a character array. Then we will convert that array into a list using Java Streams.
// Java program to convert a String to a List of Characters
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StringToListOfChar {
public static void main(String[] args) {
// Defining a string
String s = "Java";
// Convert String to List of Characters using Streams
List<Character> ch = s.chars() // Convert String to IntStream (stream of chars)
.mapToObj(c -> (char) c) // Map each int (char) to Character
.collect(Collectors.toList()); // Collect into a List
System.out.println(ch);
}
}
Output
[J, a, v, a]
Other Methods to Convert a String to a List of Characters in Java
Apart from the above method, there are various other ways to convert a string to a list of characters. Below are the examples of those methods.
1. Using charAt() Method in a Loop
In this method, we will use the charAt() method inside a loop to extract each character of the string. Then we will store it in a List.
// Java Program to Convert a String to List of Characters
// Using charAt() in a loop
import java.util.ArrayList;
import java.util.List;
public class StringToListOfChar {
public static void main(String[] args) {
String s = "Java";
List<Character> ch= new ArrayList<>();
// Extract each character using charAt() method
for (int i = 0; i < s.length(); i++) {
ch.add(s.charAt(i));
}
System.out.println(ch);
}
}
Output
[J, a, v, a]
Explanation:
- Here, we iterates over each character in the string using
charAt()
method. - Each character is added to an
ArrayList
which is then printed as a List of Characters.
2. Using AbstractList Interface
This is a more advanced and custom approach for converting a string to a list of characters.
Approach:
- Get the String.
- Use the AbstractList interface to convert the String into a List of Characters.
- Return the List.
Illustration:
// Java program to convert a String to a List of Characters
// using AbstractList
import java.util.*;
class GFG {
// Function to convert String to List of Characters
public static List<Character> StringToCharList(String s) {
return new AbstractList<Character>() {
// Overriding the get method to retrieve characters from the string
@Override
public Character get(int i) {
return s.charAt(i);
}
// Overriding the size method to return the string length
@Override
public int size() {
return s.length();
}
};
}
// Driver code
public static void main(String[] args) {
// String to be converted
String s = "Java";
// Get the List of Character
List<Character> ch = StringToCharList(s);
System.out.println(ch);
}
}
Output
[J, a, v, a]