Converting Char Array to List in Java

bourne picture bourne · Mar 23, 2013 · Viewed 96.4k times · Source

Can anyone help me and tell how to convert a char array to a list and vice versa. I am trying to write a program in which users enters a string (e.g "Mike is good") and in the output, each whitespace is replaced by "%20" (I.e "Mike%20is%20good"). Although this can be done in many ways but since insertion and deletion take O(1) time in linked list I thought of trying it with a linked list. I am looking for someway of converting a char array to a list, updating the list and then converting it back.

public class apples
{
   public static void main(String args[])
   {
      Scanner input = new Scanner(System.in);
      StringBuffer sb = new StringBuffer(input.nextLine());

      String  s = sb.toString();
      char[] c = s.toCharArray();
      //LinkedList<char> l = new LinkedList<char>(Arrays.asList(c));
      /* giving error "Syntax error on token " char",
         Dimensions expected after this token"*/
    }
}

So in this program the user is entering the string, which I am storing in a StringBuffer, which I am first converting to a string and then to a char array, but I am not able to get a list l from s.

I would be very grateful if someone can please tell the correct way to convert char array to a list and also vice versa.

Answer

hotkey picture hotkey · Dec 3, 2015

In Java 8 and above, you can use the String's method chars():

myString.chars().mapToObj(c -> (char) c).collect(Collectors.toList());

And if you need to convert char[] to List<Character>, you might create a String from it first and then apply the above solution. Though it won't be very readable and pretty, it will be quite short.