Converting Char Array to List in Java
Asked Answered
P

11

41

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.

Peritoneum answered 23/3, 2013 at 18:45 Comment(1)
you cannot use a primitive data type for your List, you need Character intead. However your approach won't work, so use e.g. ArrayUtils.toObject(char[]) from Apache Commons instead.Dees
C
83

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.

Conah answered 2/12, 2015 at 23:45 Comment(0)
D
35

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]); :)

Disarm answered 23/3, 2013 at 19:7 Comment(3)
List<char[]> asList = Arrays.asList(chars); // because this DOES compile. No this does not compile: The method asList(Object[]) in the type Arrays is not applicable for the arguments (char[])Disremember
@PhilipJ yes, it does. It does in my Eclipse. If it does NOT in yours - submit a bug report. In given code char[] becomes single object, not an array of char's. And that is even written in my answer.Disarm
Thanks. Coming from C#, Java really seems like a disgrace.Moncear
L
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.

Lenny answered 21/10, 2013 at 15:3 Comment(4)
@Cyrille Ka I did not down vote, but I'd guess it's because the answer you provided does not compile (and likely cannot be corrected to compile).Overtrump
@Overtrump As far as I can tell, and I just tried, both examples compile on Java 5 to 8, provided that "string" is a variable of type String previously initialized and Guava dependency is included in the project. Please tell me the compiler error if it fails on your machine.Lenny
Dear Cyrille - please beware of one fact. LinkedList is just for special cases.. Unless you really need it use ArrayList instead..Botheration
List with type-variable works solve that: List filterList = Arrays.asList(jTextFieldFilterSet.getText().toCharArray());Confinement
C
7

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);
Corkhill answered 22/6, 2017 at 15:23 Comment(1)
Even one step can be skipped :) var list = IntStream .range(0, myCharArray.length) .mapToObj(i -> myCharArray[i]) .collect(Collectors.toList): list.forEach(System.out::println);Hurds
R
2

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
Rodger answered 23/3, 2013 at 19:18 Comment(0)
B
2

Try Java Streams.

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

Generic arguments cannot be primitive type.

Barbiturate answered 30/7, 2022 at 12:55 Comment(0)
E
1

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://symbl.cc/en/unicode-table/#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

Elconin answered 21/8, 2019 at 4:23 Comment(0)
L
0

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;
}
Limbourg answered 25/8, 2019 at 2:11 Comment(0)
K
0

if you really want to convert char[] to List, you can use .chars() to make your string turns into IntStream, but you need to convert your char[] into String first

List<Character> charlist = String.copyValueOf(arrChr)
    .chars()
    .mapToObj(i -> (char) i)
    .collect(Collectors.toList());
Kirov answered 27/11, 2022 at 18:7 Comment(0)
N
0

Try this solution List<Character> characterList = String.valueOf(chars).chars().mapToObj(i -> (char) i).toList();

Naval answered 22/1, 2023 at 18:27 Comment(0)
C
-1

List strList = Stream.of( s.toCharArray() ).map( String::valueOf ).collect( Collectors.toList() );

Crouch answered 30/5, 2021 at 9:48 Comment(1)
No, this returns same input string wrapped in a list instead of char's list!Kingsbury

© 2022 - 2024 — McMap. All rights reserved.