I have a map
private HashMap<Character, Integer> map;
I want to convert it to array but when I do that/I get this:
Entry<Character, Integer> t = map.entrySet().toArray();
**Type mismatch: cannot convert from Object[] to Map.Entry<Character,Integer>**
Entry<Character, Integer>[] t = null;
map.entrySet().toArray(t);
**Exception in thread "main" java.lang.NullPointerException**
Entry<Character, Integer>[] t = new Entry<Character, Integer>[1];
map.entrySet().toArray(t);
**Cannot create a generic array of Map.Entry<Character,Integer>**
Entry<Character, Integer>[] t = null;
t = map.entrySet().toArray(t);
**Exception in thread "main" java.lang.NullPointerException**
So how to convert HashMap
to Array
? None of answers found in other subjects work.
In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap. This set can be passed into the ArrayList while initialization in order to obtain an ArrayList containing all the keys.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
Conversion of HashMap to ArrayList A HashMap contains key-value pairs, there are three ways to convert a HashMap to an ArrayList: Converting the HashMap keys into an ArrayList. Converting the HashMap values into an ArrayList. Converting the HashMap key-value pairs into an ArrayList.
Explanation: The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of HashMap class.
I think this will work:
Entry<Character, Integer>[] t = (Entry<Character, Integer>[])
(map.entrySet().toArray(new Map.Entry[map.size()]));
... but you need an @SuppressWarning annotation to suppress the warning about the unsafe typecast.
I am not sure exactly on the ways you tried. What I would do is
When you do that you'll get an EntrySet, so the data will be stored as Entry
So if you want to keep it in the EntrySet you can do this:
List<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>();
for(Entry<Character, Integer> entry : map.entrySet()) {
list.add(entry);
}
Also note that you will always get a different order when doing this, as HashMap isn't ordered.
Or you can do a class to hold the Entry data:
public class Data {
public Character character;
public Integer value;
public Data(Character char, Integer value) {
this.character = character;
this.value = value;
}
}
And extract it using:
List<Data> list = new ArrayList<Data>();
for(Entry<Character, Integer> entry : map.entrySet()) {
list.add(new Data(entry.getKey(), entry.getValue()));
}
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