目录
在 Java 中,字符数组、字符串数组、整型数组、字符串列表和整型列表之间可以相互转换。下面我将介绍它们之间的相互转换方法:
1. 字符数组与字符串数组之间的转换:
- 字符数组转换为字符串数组:
char[] charArray = {'a', 'b', 'c'};
String[] stringArray = new String(charArray).split("");
- 字符串数组转换为字符数组:
String[] stringArray = {"hello", "world"};
char[][] charArray = new char[stringArray.length][];
for (int i = 0; i < stringArray.length; i++) {
charArray[i] = stringArray[i].toCharArray();
}
2. 字符数组、整型数组与字符串列表的转换:
- 字符数组转换为整型数组:
char[] charArray = {'1', '2', '3'};
int[] intArray = new int[charArray.length];
for (int i = 0; i < charArray.length; i++) {
intArray[i] = Character.getNumericValue(charArray[i]);
}
- 整型数组转换为字符数组:
int[] intArray = {1, 2, 3};
char[] charArray = new char[intArray.length];
for (int i = 0; i < intArray.length; i++) {
charArray[i] = (char) (intArray[i] + '0');
}
- 字符数组转换为字符串列表:
char[] charArray = {'a', 'b', 'c'};
List<String> stringList = Arrays.stream(charArray)
.mapToObj(String::valueOf)
.collect(Collectors.toList());
3. 字符串数组、整型数组与字符串列表、整型列表的转换:
- 字符串数组转换为整型数组:
String[] stringArray = {"1", "2", "3"};
int[] intArray = Arrays.stream(stringArray)
.mapToInt(Integer::parseInt)
.toArray();
- 整型数组转换为字符串数组:
int[] intArray = {1, 2, 3};
String[] stringArray = Arrays.stream(intArray)
.mapToObj(String::valueOf)
.toArray(String[]::new);
- 字符串数组转换为字符串列表:
String[] stringArray = {"hello", "world"};
List<String> stringList = Arrays.asList(stringArray);
- 字符串列表转换为字符串数组:
List<String> stringList = Arrays.asList("hello", "world");
String[] stringArray = stringList.toArray(new String[0]);
4. 字符数组、整型数组与字符串列表、整型列表的转换:
- 字符数组转换为整型列表:
char[] charArray = {'1', '2', '3'};
List<Integer> intList = new ArrayList<>();
for (char c : charArray) {
intList.add(Character.getNumericValue(c));
}
- 整型列表转换为字符数组:
List<Integer> intList = Arrays.asList(1, 2, 3);
char[] charArray = intList.stream()
.mapToInt(Integer::valueOf)
.mapToObj(c -> (char) (c + '0'))
.toArray(Character[]::new);
- 字符串列表转换为整型数组:
List<String> stringList = Arrays.asList("1", "2", "3");
int[] intArray = stringList.stream()
.mapToInt(Integer::parseInt)
.toArray();
- 整型数组转换为整型列表:
int[] intArray = {1, 2, 3};
List<Integer> intList = Arrays.stream(intArray)
.boxed()
.collect(Collectors.toList());
5. 字符串数组、整型数组与整型列表之间的转换:
- 字符串数组转换为整型列表:
String[] stringArray = {"1", "2", "3"};
List<Integer> intList = Arrays.stream(stringArray)
.map(Integer::parseInt)
.collect(Collectors.toList());
- 整型列表转换为字符串数组:
List<Integer> intList = Arrays.asList(1, 2, 3);
String[] stringArray = intList.stream()
.map(Object::toString)
.toArray(String[]::new);