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.

J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
bourne
  • 1,083
  • 4
  • 14
  • 27
  • 2
    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](http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html) instead. – s106mo Mar 23 '13 at 18:52
  • Here is the article to **[Convert Char Array To String In Java](https://www.tutorialcup.com/java/convert-char-array-to-string-in-java.htm)** this will help you answer your question – Rahul Gupta May 14 '21 at 17:28

11 Answers11

79

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.

hotkey
  • 140,743
  • 39
  • 371
  • 326
34

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

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
dantuch
  • 9,123
  • 6
  • 45
  • 68
  • List 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[]) – Philip Puthenvila Aug 08 '13 at 01:45
  • @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. – dantuch Aug 26 '13 at 15:19
  • Thanks. Coming from C#, Java really seems like a disgrace. – alelom Jan 31 '21 at 18:08
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.

Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
  • @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). – mbmast Nov 30 '16 at 18:47
  • @mbmast 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. – Cyrille Ka Jan 06 '17 at 14:56
  • Dear Cyrille - please beware of one fact. LinkedList is just for special cases.. Unless you really need it use ArrayList instead.. – Polostor Apr 29 '19 at 18:50
  • List with type-variable works solve that: List filterList = Arrays.asList(jTextFieldFilterSet.getText().toCharArray()); – Jaja Jun 15 '20 at 14:16
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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 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); – Gulbala Salamov Nov 08 '22 at 15:51
1

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
Community
  • 1
  • 1
A4L
  • 17,353
  • 6
  • 49
  • 70
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://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

Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
1

Try Java Streams.

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

Generic arguments cannot be primitive type.

Isuru
  • 21
  • 5
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;
}
tanmay_garg
  • 377
  • 1
  • 13
0

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

Jananda
  • 11
  • 1
  • 5
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());
Ryve
  • 1
0

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