How do I initialize an ArrayList from a char array?
There is such a code:
List<Character> charArray = new ArrayList<>(Arrays.asList(string.toCharArray()));
But a compile-time error occurs. Why?(maybe because of Character
and char
?) But why does everything work with int
?
List<Integer> charArray = new ArrayList<>(Arrays.asList(23,22,32));
UPD: Forgot to add without using a loop.
0
Author: Anton Sorokin, 2018-08-21
2 answers
In Java 8, you can do this
List<Character> chars = string.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
2
Author: zolt, 2018-08-21 05:40:01
List<Character> chars = new ArrayList<>();
for (char c : string.toCharArray()) {
chars.add(c);
}
0
Author: Sergey Gornostaev, 2018-08-21 06:11:18