0

Is there anyway to convert a String to an ArrayList<Character> without using regex.

For example:

"abc".methodHere == ArrayList<Character>["a", "b", "c"]

This link converts a String to an ArrayList<String> and this link uses Array and not ArrayList

Community
  • 1
  • 1
  • Can you go from Array to ArrayList? https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...) – marisbest2 Mar 14 '17 at 20:24

4 Answers4

1

You could get the stream of characters and collect to a list:

List<Character> chars = s.chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.toList());

If you want an ArrayList specifically, you could collect to an ArrayList:

List<Character> chars = s.chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.toCollection(ArrayList::new));
janos
  • 120,954
  • 29
  • 226
  • 236
0

Iterate through the characters in the string by index

ArrayList<Character> chars = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
   chars.add(str.charAt(i));
// do whatever with the chars list
BGRT
  • 116
  • 6
0

A different answer from the ones already provided:

ArrayList<Character> list = (ArrayList<Character>)"abc".chars().mapToObj(i -> (char)i).collect(Collectors.toList());
VHS
  • 9,534
  • 3
  • 19
  • 43
0

Alternatively, you can do

ArrayList<Character> chars =
     new ArrayList<>(Chars.asList(string.toCharArray()));

You need to import com.google.common.primitives.Chars; from Guava library.

Peter L
  • 302
  • 1
  • 6