I have a hash map and I'm trying to convert the keys to a list. Here's the code:
List<ARecord> recs = new ArrayList<ARecord>(); HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>(); for(ARecord records:recs){ if(!uniqueRecs.containsKey(records.getId())){ uniqueRecs.put(records.getId(), records); } }
When I try to do
List<ARecord> finalRecs = new ArrayList<ARecord>(uniqueRecs.keySet());
The error:
The constructor ArrayList(Set) is undefined".
How can I convert Hashmap keys to List<ARecord>
finalRecs?
We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.
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.
Yes you can have ArrayList s as a keys in a hash map, but it is a very bad idea since they are mutable. If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.
Your uniqueRecs
has String
type of the key. You have to do:
List<String> keys = new ArrayList<>(uniqueRecs.keySet());
or
List<ARecord> values = new ArrayList<>(uniqueRecs.values());
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