Java collections convert a string to a list of characters

Viewed 186012

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());
11 Answers
List<String> result = Arrays.asList("abc".split(""));

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

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())

To get a list of Characters / Strings -

List<String> stringsOfCharacters = string.chars().
                                   mapToObj(i -> (char)i).
                                   map(c -> c.toString()).
                                   collect(Collectors.toList());
Related