I have the following HashMap that I insert character-int pairs in a method and return this hashmap:
HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
for (...) {
hmap.put(string[i], number[i]);
}
However, when I want to convert this returned hashmap keys to char array, it includes also brackets and commas:
char[] charArray = myReturnedHashMap.keySet().toString().toCharArray();
//it returns 8 char "[ A , B , C , ]" instead of just "A B C"
So, how can I fix it?
Update: On the other hand, I am not sure if HashMap is a good idea to use in this scenario. I have a loop and I just need to return char and int value pairs. Then in the other method I convert char values to a chararray. Any idea?
Your problem is the call of 'keySet().toString()' - this creates the string representation of the map.
I think you want something like this:
Map<Character, Integer> hmap = new HashMap<Character, Integer>();
hmap.put('c', 1);
hmap.put('d', 2);
hmap.put('e', 3);
Character[] charArray = hmap.keySet().toArray(new Character[0]);
Edit: If you need the keys sorted, you can use a TreeMap instead of a HashMap. But be aware, if you are dealing with characters and expecting language specific sorting you need a Collator for sorting in the TreeMap.
This is an easy, very resuable (works with all kind of maps) and easily sortable solution:
char[] charArray = map.keySet().stream()
.map(String::valueOf)
.collect(Collectors.joining()).toCharArray();
Here's the fastest solution:
char[] chars = new char[map.size()];
int i = 0;
for (Character c : map.keySet()) {
chars[i++] = c;
}
The keys in a HashMap aren't sorted. Use another map implementation or sort the stream .
You can use toArray()
with the caveat that it'll return an Object[]
array.
Object[] charArray = myReturnedHashMap.keySet().toArray();
test demo from jshell:
jshell> HashMap<Character, Integer> a = new HashMap<>()
a ==> {}
jshell> a.put('a', 1)
$11 ==> null
jshell> a.keySet()
$12 ==> [a]
jshell> a.keySet().to
toArray( toString()
jshell> a.keySet().toArray()
$13 ==> Object[1] { 'a' }
jshell> a.keySet().toArray()[0]
$14 ==> 'a'
jshell> (char)a.keySet().toArray()[0]
$15 ==> 'a'
The toString()
in unnecessary in your case. You just want to take that Set
and convert it to an Array. Something like this seems to work just fine:
HashMap<Character, Integer> hmap = new HashMap<Character, Integer>();
hmap.put('a',1);
hmap.put('b',1);
hmap.put('c',1);
Set<Character> characters = hmap.keySet();
Character[] chars = new Character[characters.size()];
characters.toArray(chars);
System.out.println(Arrays.toString(chars));
use toArray()
Map<Character, Integer> map = new HashMap<Character, Integer>();
map.put('a', 1);
map.put('b', 1);
Character[] charArray = map.keySet().toArray(Character[]::new);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.