Converting Char Array to List in Java

夙愿已清 提交于 2019-11-29 01:48:52

问题


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.


回答1:


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.




回答2:


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:


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.




回答4:


Now I will post this answer as a another option for all those developers that are not allowed to use any lib but ONLY the Power of java 8:)

char[] myCharArray = { 'H', 'e', 'l', 'l', 'o', '-', 'X', 'o', 'c', 'e' };

Stream<Character> myStreamOfCharacters = IntStream
          .range(0, myCharArray.length)
          .mapToObj(i -> myCharArray[i]);

List<Character> myListOfCharacters = myStreamOfCharacters.collect(Collectors.toList());

myListOfCharacters.forEach(System.out::println);



回答5:


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



回答6:


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




回答7:


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;
}


来源:https://stackoverflow.com/questions/15590675/converting-char-array-to-list-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!