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());
List<String> myList = new ArrayList<String>(Arrays. asList(s. split(","))); Arrays.
1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc. 2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays. asList() method.
The ArrayList constructor is an effective way to get the contents of a Collection into a new ArrayList.
Here's how you convert a String to a char array: String str = "someString"; char[] charArray = str. toCharArray(); I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray() ) and compile errors like the one you have above.
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());
You will have to either use a loop, or create a collection wrapper like Arrays.asList
which works on primitive char arrays (or directly on strings).
List<Character> list = new ArrayList<Character>(); Set<Character> unique = new HashSet<Character>(); for(char c : "abc".toCharArray()) { list.add(c); unique.add(c); }
Here is an Arrays.asList
like wrapper for strings:
public List<Character> asList(final String string) { return new AbstractList<Character>() { public int size() { return string.length(); } public Character get(int index) { return string.charAt(index); } }; }
This one is an immutable list, though. If you want a mutable list, use this with a char[]
:
public List<Character> asList(final char[] string) { return new AbstractList<Character>() { public int size() { return string.length; } public Character get(int index) { return string[index]; } public Character set(int index, Character newVal) { char old = string[index]; string[index] = newVal; return old; } }; }
Analogous to this you can implement this for the other primitive types. Note that using this normally is not recommended, since for every access you would do a boxing and unboxing operation.
The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With