[java] Java collections convert a string to a list of characters

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?

List<Character> charList = new ArrayList<Character>("abc".toCharArray());

This question is related to java string collections

The answer is


IntStream can be used to access each character and add them to the list.

String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));

In Java8 you can use streams I suppose. List of Character objects:

List<Character> chars = str.chars()
    .mapToObj(e->(char)e).collect(Collectors.toList());

And set could be obtained in a similar way:

Set<Character> charsSet = str.chars()
    .mapToObj(e->(char)e).collect(Collectors.toSet());

List<String> result = Arrays.asList("abc".split(""));

You can do this without boxing if you use Eclipse Collections:

CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();

Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.

ImmutableList<Character> immutableList = abc.collect(Character::valueOf);

If you want to return a boxed List, Set or Bag of Character, the following will work:

LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();

Note: I am a committer for Eclipse Collections.


The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.

List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar) 
{
    characterList.add(aChar); //  autoboxing 
}

Use a Java 8 Stream.

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

Breakdown:

myString
    .chars() // Convert to an IntStream
    .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
    .collect(Collectors.toList()); // Collect in a List<Character>

(I have absolutely no idea why String#chars() returns an IntStream.)


Using Java 8 - Stream Funtion:

Converting A String into Character List:

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

Converting A Character List into String:

 String givenStringVariable =  characterList
                                            .stream()
                                            .map(String::valueOf)
                                            .collect(Collectors.joining())

The most straightforward way is to use a for loop to add elements to a new List:

String abc = "abc";
List<Character> charList = new ArrayList<Character>();

for (char c : abc.toCharArray()) {
  charList.add(c);
}

Similarly, for a Set:

String abc = "abc";
Set<Character> charSet = new HashSet<Character>();

for (char c : abc.toCharArray()) {
  charSet.add(c);
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?