1

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?

7
  • @am0awad I think you did not see the comment line it returns 8 char "[ A , B , C , ]" instead of just "A B C". Commented Apr 30, 2020 at 9:26
  • It's because you're converting keys into a string representation which adds , and [ ] for pretty output and then doing .toCharArray() on top of the pretty output. What you need to do is iterate on the keySet() and put them in a char array Commented Apr 30, 2020 at 9:27
  • Has any Java Developer got any idea? :( Commented Apr 30, 2020 at 9:28
  • @sonnet Is there any iteration via lambda expression e.g. map(m=>m....)? Any example pls? Commented Apr 30, 2020 at 9:29
  • 1
    don't use the toString method for conversion Instead use the toArray() method on the Set returned by myReturnedHashMap.keySet() (Note that this will give you a Character[] but if you want/need to convert that to a char[] I'm sure you can find some solution already here on SO. Commented Apr 30, 2020 at 9:30

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

That produces Character[] instead of char[].
@steffen Yes, but I get the result correctly, Is there any problem with this implementation?
@TomStroemer Sorry, but it returns exception. Any idea?
@hexadecimal No, the solution is fine, as long as the order doesn't matter and your code works with both char[] and Character[]!
@hexadecimal yes, that is true. HashMap does not guarantee any order for its keys but of course it will never mix up the key-value mapping (otherwise the whole class would be useless).
|
1

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.

7 Comments

Seems very smart solution, but unfortunately "The method collect(Collector<? super Character,A,R>) in the type Stream<Character> is not applicable for the arguments (Collector<CharSequence,capture#1-of ?,String>)" error thrown. Any idea?
@hexadecimal Sorry, I had a Map<String, String>.
Doesn't this create a lot of unnecessary strings? I'd just use a for-each loop to loop through the key set (assuming order doesn't matter).
@Sweeper It's one solution, that works for all kind of Maps, allows sorting and produces the desired char[] instead of Character[].
@steffen Dear Steffen, I encountered sorting error that you warned. The order of the elements are changed and for this reason I need to sort items. I look at the link, but could not sort. Could you also post the sorting example to your answer. I see that it is serious issue. Thanks a lot.
|
0

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

1 Comment

@am0awad the array contains only 3 elements, I'm just printing it to show them.
0

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'

3 Comments

I already tried it but throws error when getting char value like (char) charArray[0].
what error is it. i tried this and mine seemed to work fine.
i've updated the demo from my jshell to demo that the solution works.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.