Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hash map keys into list?

Tags:

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?

like image 526
Jay Avatar asked Aug 04 '15 21:08

Jay


People also ask

Can we convert map to list in Java?

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.

How do I add a HashMap to a list?

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.

Can HashMap have list as key?

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.


1 Answers

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()); 
like image 86
ka4eli Avatar answered Oct 12 '22 02:10

ka4eli