Converting Char Array to List in Java

2020-02-23 05:38发布

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.

7条回答
Deceive 欺骗
2楼-- · 2020-02-23 06:04

Because char is primitive type, standard Arrays.asList(char[]) won't work. It will produce List<char[]> in place of List<Character> ... so what's left is to iterate over array, and fill new list with the data from that array:

    public static void main(String[] args) {
    String s = "asdasdasda";
    char[] chars = s.toCharArray();

    //      List<Character> list = Arrays.asList(chars); // this does not compile,
    List<char[]> asList = Arrays.asList(chars); // because this DOES compile.

    List<Character> listC = new ArrayList<Character>();
    for (char c : chars) {
        listC.add(c);
    }
}

And this is how you convert List back to array:

    Character[] array = listC.toArray(new Character[listC.size()]);




Funny thing is why List<char[]> asList = Arrays.asList(chars); does what it does: asList can take array or vararg. In this case char [] chars is considered as single valued vararg of char[]! So you can also write something like

List<char[]> asList = Arrays.asList(chars, new char[1]); :)

查看更多
劫难
3楼-- · 2020-02-23 06:04

I guess the simplest way to do this would be by simply iterating over the char array and adding each element to the ArrayList of Characters, in the following manner:

public ArrayList<Character> wordToList () {
    char[] brokenStr = "testing".toCharArray();
    ArrayList<Character> result = new ArrayList<Character>();
    for (char ch : brokenStr) {
        result.add(ch);
    }
    return result;
}
查看更多
Juvenile、少年°
4楼-- · 2020-02-23 06:14

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.

查看更多
我想做一个坏孩纸
5楼-- · 2020-02-23 06:15

All Operations can be done in java 8 or above:

To the Character array from a Given String

char[] characterArray =      myString.toCharArray();

To get the Character List from given String

 ArrayList<Character> characterList 
= (ArrayList<Character>) myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());

To get the characters set from given String Note: sets only stores unique value. so if you want to get only unique characters from a string, this can be used.

 HashSet<Character> abc = 
(HashSet<Character>) given.chars().mapToObj(c -> (char)c).collect(Collectors.toSet()); 

To get Characters in a specific range from given String : To get the character whose unicode value is greater than 118. https://unicode-table.com/en/#basic-latin

ASCII Code value for characters * a-z - 97 - 122 * A-Z - 65 - 90

 given.chars().filter(a -> a > 118).mapToObj(c -> (char)c).forEach(a -> System.out.println(a));

It will return the characters: w,x, v, z

you ascii values in the filter you can play with characters. you can do operations on character in filter and then you can collect them in list or set as per you need

查看更多
祖国的老花朵
6楼-- · 2020-02-23 06:17

Another way than using a loop would be to use Guava's Chars.asList() method. Then the code to convert a String to a LinkedList of Character is just:

LinkedList<Character> characterList = new LinkedList<Character>(Chars.asList(string.toCharArray()));

or, in a more Guava way:

LinkedList<Character> characterList = Lists.newLinkedList(Chars.asList(string.toCharArray()));

The Guava library contains a lot of good stuff, so it's worth including it in your project.

查看更多
走好不送
7楼-- · 2020-02-23 06:17

You cannot use generics in java with primitive types, why?

If you really want to convert to List and back to array then dantuch's approach is the correct one.

But if you just want to do the replacement there are methods out there (namely java.lang.String's replaceAll) that can do it for you

private static String replaceWhitespaces(String string, String replacement) {
    return string != null ? string.replaceAll("\\s", replacement) : null;
}

You can use it like this:

StringBuffer s = new StringBuffer("Mike is good");
System.out.println(replaceWhitespaces(s.toString(), "%20"));

Output:

Mike%20is%20good
查看更多
登录 后发表回答