Java 把一个字符串转换为一个字符列表
给定一个字符串,任务是在Java中把它转换成一个字符列表。
例子。
输入: String = “Geeks”
输出: [G, e, e, k, s]
s人: String = “GeeksForGeeks”
输出: [G, e, e, k, s, F, o, r, G, e, e, k, s]
以下是各种方法。
- Naive 方法
步骤:
- 获取字符串。
- 创建一个空的字符列表。
- 将字符串的每个字符添加到列表中。
- 返回列表。
下面是上述方法的实现。
// Java program to illustrate
// Converting a String to a List
// of Characters
import java.util.*;
// Java program to convert
// a String to a List of Characters
class GFG {
// Function to convert String
// to List of Characters
public static List<Character>
convertStringToCharList(String str)
{
// Create an empty List of character
List<Character> chars = new ArrayList<>();
// For each character in the String
// add it to the List
for (char ch : str.toCharArray()) {
chars.add(ch);
}
// return the List
return chars;
}
// Driver code
public static void main(String[] args)
{
// Get the String to be converted
String str = "Geek";
// Get the List of Character
List<Character>
chars = convertStringToCharList(str);
// Print the list of characters
System.out.println(chars);
}
}
输出:
[G, e, e, k]
- 使用 Java 8 Stream:
步骤:
- 获取字符串。
- 创建一个字符列表。
- 使用chars()方法将String转换为IntStream。
- 使用mapToObj()方法将IntStream转换为Stream。
- 使用collect()方法将元素收集为一个字符列表。
- 返回列表。
下面是上述方法的实现。
// Java program to illustrate
// Converting a String to a List
// of Characters
import java.util.*;
import java.util.stream.Collectors;
// Java program to convert
// a String to a List of Characters
class GFG {
// Function to convert String
// to List of Characters
public static List<Character>
convertStringToCharList(String str)
{
// Create an empty List of character
List<Character> chars = str
// Convert to String to IntStream
.chars()
// Convert IntStream to Stream<Character>
.mapToObj(e -> (char)e)
// Collect the elements as a List Of Characters
.collect(Collectors.toList());
// return the List
return chars;
}
// Driver code
public static void main(String[] args)
{
// Get the String to be converted
String str = "Geek";
// Get the List of Character
List<Character>
chars = convertStringToCharList(str);
// Print the list of characters
System.out.println(chars);
}
}
输出:
“`java [G, e, e, k]
<pre><code class=" line-numbers"><br />3. **Using Java 8 Stream:**
步骤:
1. 获取字符串。
2. 使用AbstractList接口将字符串转换为字符列表。
3. 返回列表。
下面是上述方法的实现。
“`java
import java.util.*;
// Java program to convert
// a String to a List of Characters
class GFG {
// Function to convert String
// to List of Characters
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();
}
};
}
// Driver code
public static void main(String[] args)
{
// Get the String to be converted
String str = “Geek”;
// Get the List of Character
List<Character>
chars = convertStringToCharList(str);
// Print the list of characters
System.out.println(chars);
}
}
输出:
[G, e, e, k]