在Java中将Char数组转换为List

在Java中将Char数组转换为List

问题描述:

任何人都可以帮助我并告诉如何将 char 数组转换为列表,反之亦然。
我正在尝试编写一个用户输入字符串的程序(例如Mike is good),在输出中,每个空格都被%20(即Mike%20is%20good)。虽然这可以通过多种方式完成,但由于插入和删除在链表中需要O(1)时间,我想用链表进行尝试。我正在寻找将 char 数组转换为列表,更新列表然后将其转换回来。

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"*/
    }
}

所以在这个程序中用户输入的字符串,我存储在 StringBuffer 中,我首先转换为字符串,然后转换为 char 数组,但我无法获得列表 l 来自 s

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.

如果有人可以告诉正确的转换方法,我将非常感激 char 数组到列表,反之亦然。

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

在Java 8中, CharSequence :: chars 方法提供了一种将 String 转换为 List< Character>的单行方式;

In Java 8, CharSequence::chars method provides a one-line way to convert a String into List<Character>:

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

如果你需要转换 char [] 列表<字符> ,您可以先从它创建字符串,然后应用上述解决方案。虽然它不太可读和漂亮,但它会很短。

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.